9.2  Java Script - String Object

Index Code Tester

OBJECTIVE

DISCUSSION

String Object 

var sName = "jobob"
alert(sName)
sName.toUpperCase()
alert(sName)  //Has sName changed?
sName = sName.toUpperCase();
alert(sName)
alert(sName.charAt(1))
alert(sName.substring(1,3)) //Extracts string from character 1 through character 3
alert(sName.substr(1,3)) //Extracts 3 characters starting at position 1
alert(sName.bold())  //What if we use document.write instead of alert?
document.write(sName.bold())
alert(sName.replace("J", "Y"))
alert(sName)
  

   

EXERCISES

1.  List methods of the String object.  Indicate if the method is for formatting or not.  Formatting methods are those which change how the string appears.

2.  What is the difference between the substring() and substr() methods?  Experiment to ensure that you understand them.

3.  What does the concat() method do?  Do not say that it "Returns two concatenated strings".  Experiment to ensure that you understand it.

4.  What do indexOf() and charAt() do?  Experiment to ensure that you understand them.

5.  Write a function called viewCharacters(sString) that displays each character in sString one at a time in an alert. 

6.  Write a function that accepts a string and then returns the string with all numbers removed.

7. Write a function that accepts a string and then creates a new string with each character randomly formatted using at least 4 of the format methods.  Check out the following example.  Copy and paste it into CodeTester.  This example formats every other character as sub() or sup().

var sName = "jobob"
var sString = new String()
var x = new String()
for (i = 0; i < sName.length; i++) {
   if (i % 2 == 0) {
       x = sName.charAt(i)
       sString = sString + x.sub()
    }
   else {
       x = sName.charAt(i)
       sString = sString + x.sup()

    }

}
document.write(sString)

LINKS AND HELP

http://www.w3schools.com/js/js_string.asp