Tuesday, December 25, 2012

String object


The most commonly used Javascript String objects are listed below with the usage.

1. length()
    Length function is used to determine the length of string but it doesn't use the index count. Always length of string is one more than the index of the last character. for example

var x="Javascript"; 
/* index starts with 0 and the last index is 9, but length would be last index +1 which is (9+1=10). hence length of the string is 10 and not 9.*/
var x="Javascript";
alert(x.length()); //output is 10;

2. charAt()
    This function take one parameter which would be the index value and identifies the corresponding character.

var x="javascript";
alert(x.charAt(5));//output would be c

3. indexOf()
    This string function provides the corresponding index value of the string.


var x="javascript";
alert(x.indexOf('s'));//output would be 4

4. LastIndexOf()

   This string function provides the corresponding index value of the last occurrence of the character specified.


var x="javascript";
 /* we know that character 'a' appears twice in the string, inorder to track the index value of the last occurence of the character 'a', we use this function.*/
alert(x.lastIndexOf('a'));//output would be 3

5. substring()
    If you would like to retrieve a part of the string then this function could be used, unlike others this function requires 2 parameter which holds the index values of the desired string.

var x="javascript";
alert(x.substring(4,10)); //output would be script

6. split()

      Split function takes one parameter as delimiter and split the string into array of strings, for example.

var x="informative javascript";
alert(x.split(" "));
/* firstly i have used space as the delimiter, now by applying the split function, it splits the string after space and adds them to array.note the output would be (infirmative,javascript)*/

7. toUpperCase(),toLowerCase()
    These functions are used to transform the given string to uppercase and lower case.
 
var x="JavaScript";
alert(x.toUpperCase());//output would be JAVASCRIPT.
alert(x.toLowerCase());//output would be javascript.

Informative Javascript

1 comment: