Changes

Jump to: navigation, search

JavaScript String Object

1,499 bytes added, 19:14, 27 April 2007
Performing Conversions on String Objects
=== Performing Conversions on String Objects ===
The conversion methods of the String object are accessed in the same way as all other String object methods, and can be used to perform such taska tasks as converting the string to all upper case or all lower case.
<pre>
myString = new String ("This Is My String");
var lowerCase = myString.toLowerCase(); // lowerCase variable now contains 'this is my string'
 
</pre>
 
=== Manipulating Strings with the String Object ===
 
One of the most powerful features of the JavaScript String Object in the ability to manipulate strings. This includes breaking a string up into multiple sections, extracting fragments of a string and finding whterh whether a particular string sequence in contained in a string.
 
To extract a single character from a specific index into the string:
 
</pre>
 
myString = new String ("This is my string");
var thirdChar = myString.charAt(2); // returns 'i' which is the thrid character (remember the first character is index 0!)
 
</pre>
 
To extract a section of the string between two index points:
 
</pre>
 
myString = new String ("This is my string");
var partString = myString.substring(5, 10); // returns 'is my' which is the text between index points 5 and 10
 
</pre>
 
To extarct a given number of characters after an index point:
 
<pre>
 
myString = new String ("This is my string");
var partString = myString.substr(5, 2); // returns 'is' which is conists of the 2 characters after index point 5
 
</pre>
 
To find where a particular string appears within a String object:
 
<pre>
 
myString = new String ("This is my string");
var location = myString.indexOf ("my"); // returns 8 which is the index position where 'my' begins
 
</pre>
 
To replace part of the string with another string:
 
<pre>
 
myString = new String ("This is my string");
var newString = myString.replace ("my", "your"); // returns 'This is your string'
</pre>

Navigation menu