CodingBison

In this section, we discuss various methods provided by the String object. We organize methods provided by String.prototype into five sets. The first set discusses basic String methods like getting a character of the string, getting the string value of a String object etc. The second set focuses on methods that manipulate string case (lower/upper). The next set provides methods that update, split, slice, and trim strings. The fourth set provides methods that search, match, and retrieve substrings from a given larger string value. The last set focuses on methods that provide an HTML wrapper to strings and thus, help us format the strings as per HTML syntax.

Basic Methods

The first set discusses some of the basic methods provided by String.prototype's methods: charAt(), charCodeAt(), toString(), and valueOf().

The method charAt() takes an index and returns a string holding the character present at the passed index. Since string values are arrays, the first character in a String value has an index of 0, the second character has an index of 1, and so on. The charCodeAt() returns the ASCII code (a number) of the character present at that index. Next, toString() returns the string value of the String object. Lastly, the valueOf() method is same as toString() for String objects since the valueOf() also returns the (string) value of a String object.

Let us see an example that provides usage of these basic methods. Note that this method uses the length property of the String object and this is not the same as the length property that is natively available to a string type.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define a String object.
 var sObj = new String("The dragon grew furious");

 elem.innerHTML += sObj.length;        // prints 23 
 elem.innerHTML += sObj.charAt(6);     // prints char 'a' 
 elem.innerHTML += sObj.charCodeAt(6); // prints ASCII code of 'a', which is 97 
 elem.innerHTML += sObj.toString();    // prints "The dragon grew furious"
 elem.innerHTML += sObj.valueOf();     // prints "The dragon grew furious"

 </script>
 </html>

Methods for Case-Manipulation of Strings

The second set describes methods that allow us to manipulate case (lower/upper) for strings: toLowerCase(), toUpperCase(), toLocaleLowerCase(), and toLocaleUpperCase().

Method toLowerCase() converts all characters of a given String value into lower-case characters. On the other hand, toUpperCase() converts all characters of a given String value into upper-case characters. These methods also have two counterparts: toLocaleLowerCase() and toLocaleUpperCase(). These local methods typically provide correct results by taking into account the local environment of the host (in this case, browser).

We provide a simple example that demonstrates the usage of these methods.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define a String object.
 var sObj = new String("KilGharRah"); 

 var x = sObj.toLowerCase();        
 elem.innerHTML += x;          // prints "kilgharrah"
 elem.innerHTML += (typeof x); // prints "string" 
 elem.innerHTML += sObj;       // prints "KilGharRah" since sObj is unmodified.

 elem.innerHTML += sObj.toUpperCase();       // prints "KILGHARRAH"
 elem.innerHTML += sObj.toLocaleLowerCase(); // prints "kilgharrah" 
 elem.innerHTML += sObj.toLocaleUpperCase(); // prints "KILGHARRAH" 

 </script>
 </html>

Methods to Update, Split, and Slice Strings

The next set discusses methods for updating, splitting, and slicing String objects: concat(), replace(), trim(), split(), and slice(). All of these methods return an updated string and keep the original String value intact.

Method concat() can take multiple arguments and returns a string value that concatenates the original String value with the passed arguments (in the same order as passed).

Method replace() takes a search value and a replace value that replaces the searched value, if it finds it. The replace value replaces all occurrences of the searched value. Once complete, this method returns a new string value which equals the original String value plus the replacement.

Method trim() removes leading and trailing white spaces from the String value. This method also provides two other variants: trimLeft() and trimRight(); these methods strip white-spaces from the left (beginning) and the right side (end) of the String respectively.

Method split() accepts two arguments: a separator and a limit. Based on the separator, this method splits the String value of the object and puts them in an array. If we specify the limit, then it places only as many elements as are specified by the limit; if we don't specify the limit, then it places all the split elements into the array. Further, if we do not specify the separator, then split() methods returns an array consisting of only one element: the string value of the String object.

The last method, slice() takes two arguments: start index and end index. It returns a string value that has all the characters starting at the start index and with index less than the passed end index.

Let us go through a simple example to see typical usage of these methods. We print the output of this example as comments.

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define a String object.
 var sObj = new String("Frodo");

 elem.innerHTML += sObj.concat(" was a hobbit");           // prints "Frodo was a hobbit"
 elem.innerHTML += sObj.concat(" was a", " good hobbit");  // prints "Frodo was a good hobbit" 
 elem.innerHTML += sObj.replace("Frodo", "Bilbo Baggins"); // prints "Bilbo Baggins" 

 // Define another String object.
 var sObj2 = new String("Frodo was a good hobbit");

 a = sObj2.split(" ");         // a equals ["Frodo", "was", "a", "good", "hobbit"]
 b = sObj2.slice(0, 5);        // b is a string and equals "Frodo"

 // Define yet another String object.
 var sObj3 = new String("  Norse mythology   contains nine worlds  "); 

 elem.innerHTML += sObj3.length; // prints 42
 x = sObj3.trim();               
 elem.innerHTML += x.length;     // prints 38

 </script>
 </html>

Methods for Searching, Matching, and Finding Substrings

The fourth set covers String.prototype's methods that allow us to search, match, and find substrings: search(), match(), indexOf(), lastIndexOf(), substring(), and substr().

Method search() accepts a string or a character and then returns the index (a number) at which it first finds the string or the character. This method can also accept a regular expression. Method match() uses a RegExp to find a match. If it does, it returns an array of all the matches, else it returns a "null".

String.prototype provides two methods for finding out indexes of a substring: indexOf() and lastIndexOf(). Both of these methods take a substring (or a character) as an argument and return the index of their first occurrence. indexOf() starts the search from the beginning of the array and progresses towards the end of the array. On the other hand, lastIndexOf() starts its search at the end of the array and progresses towards the beginning of the array. If either of these functions do not find the substring, then they return (-1).

Method substring() takes two arguments: start index and end index; it returns a smaller string value of String that starts at start index and contains all characters that have indexes less than the passed end index. In this regard, substring() is similar to the slice() method. Further, if we do not specify the second argument, then it returns a substring starting at the start index and includes the rest of the String value.

The last method, substr() also takes two arguments: start index and length. It returns a substring that starts at the start index and then it returns the same number of characters as is specified by the limit. Once again, if we fail to specify the "limit", then this method returns the entire substring starting at the start index.

Here is an example:

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define a String object.
 var sObj = new String("Thor is the Norse God of thunder and lightning");

 elem.innerHTML += sObj.search("thunder"); //prints 25 
 elem.innerHTML += sObj.search('G');       //prints 18 
 elem.innerHTML += sObj.search("Rain");    //prints -1 

 elem.innerHTML += sObj.match("thunder");  //prints ["thunder"]
 elem.innerHTML += sObj.match("rain");     //prints "null"

 elem.innerHTML += sObj.indexOf('r');      //prints 3 
 elem.innerHTML += sObj.lastIndexOf('r');  //prints 31 

 elem.innerHTML += sObj.substring(12, 18); //prints "Norse"
 elem.innerHTML += sObj.substr(12, 5);     //prints "Norse"

 </script>
 </html>

HTML Wrapper Methods

The last set discusses various String methods that allow us to provide an HTML wrapper to the String value. Some of these methods are: bold(), big(), small(), italics(), strike, fontcolor(), and fontsize(). All of these methods return a new string value and leave the original String value intact.

Let us provide a brief summary of these methods.

Method bold() returns the String value in a bold format for the browser. Methods big() and small() change the size of the font to big and small respectively. We can also do the same by using fontsize(), where we can pass font size and thus, adjust if the font to big or small. Method italics() returns an italicized format of the String value and the method strike() returns strikes the String value and then returns the new string. Lastly, method fontcolor() takes the name of the color as an argument and returns the String value in the specified color.

Here is an example:

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Define a String object.
 var sObj = new String("Realizing all the wrongs done, the dragon became furious");

 elem.innerHTML += sObj.bold() + "<br>";
 elem.innerHTML += sObj.big() + "<br>";       
 elem.innerHTML += sObj.small() + "<br>";    
 elem.innerHTML += sObj.italics() + "<br>"; 
 elem.innerHTML += sObj.strike() + "<br>";  
 elem.innerHTML += sObj.fontcolor("red") + "<br>";
 elem.innerHTML += sObj.fontsize(5) + "<br>"; 

 </script>
 </html>

When we run this example in a browser, here is the output displayed by the browser:



Figure: Using HTML wrapper methods





comments powered by Disqus