String Manipulation Functions
String variables in JavaScript have a number of very useful string functions. Here's a sample of the most commonly used:
Operation / Function | Example |
Concatenation (+) | var S1 = "Customer"; var S2 = "123456"; var S3 = S1 + " " + S2 + "could not be found";
puts Customer 123456could not be found in variable S3. |
IndexOf – finds first occurrence of a string in a string | /* 012345678901 */ var S1 = "ABCDHELLOABC"; var pos = S1.indexOf("HELLO");
will put the number 4 into variable pos. |
lastIndexOf - finds last occurrence of a string in a string | /* 012345678901 */ var S1 = "ABCDHELLOABC"; var pos = S1.lastIndexOf("AB");
will put the number 9 into variable pos. |
charAt – returns the character at a specific position in a string | /* 012345678901 */ var S1 = "ABCDHELLOABC"; var S2 = S1.charAt(4); var S3 = S1.charAt(9);
will put "H" into S2 and "A" into S3. |
length – returns the length of a string | /* 012345678901 */ var S1 = "ABCDHELLOABC"; var I = S1.length;
will put the number 11 into variable I. |
substring – returns the substring of string using a starting and ending point. | /* 01234567789 */ var a = "Hello World"; var b = a.substring(4,8);
will put "o Wor" into b.
|
substr – returns the substring of a string using a starting position and a length | /* 01234567789 */ var a = "Hello World"; var b = a.substr(2,3);
will put "llo" into b.
|
toLowerCase – returns the lowercase of string | var a = "Hello World"; var b = a.toLowerCase();
will put "hello world" into b.
|
toUpperCase – returns the uppercase of a string | var a = "Hello World"; var b = a.toUpperCase();
will put "HELL WORLD" into b.
|
There are more string functions like these available. See:
http://www.w3schools.com/jsref/jsref_obj_string.asp for more details.