String functions in JavaScript by example
Apr 2, 2013 00:00 · 302 words · 2 minute read
You can test these functions online at jsbin.com.
Get the character at a specific index
var name = "amir";
alert("charAt(0): " + name.charAt(0));
It will return “a” as it is the first character of “amir”.
Find the index of character in string
var name = "amir";
alert("indexOf('m'):" + name.indexOf('m'));
it will return 1 as “m” is the second character of the “amir” and it start counting from 0.
Replace two characters in the string
var name = "amir";
name = name.replace("a", "m");
alert("replace('a','m'): " + name.charAt(0));
It will replace the first character with the second one i.e. “a” with “m”. Therefore it will alert “m” as the first character of “amir”.
Slice a string
var name = "amir";
alert("slice(0,3) :" + name.slice(0, 3));
it will start from the 0 position of the string and return the first three character of it. Therefore it will return “ami”.
Search of the index of character in the string
var name = "amir";
alert("search(/m/) : " + name.search(/m/));
It will search for the position of the occurrence of “m” in “amir” and return 1.
Split string into array
var name = "amir";
alert("split('m') :" + name.split('m'));
it will split the “amir” into two substring from the “m”. Therefore it will return “a” and “ir” as an array.
Convert string to uppercase
var name = "amir";
alert("toUpperCase :" + name.toUpperCase());
It will convert the “amir” into upper case level character and will return “AMIR”.
Check the type with isNaN
you can check if a variable is a string or not .
alert("is string not a number ? :" + isNaN("test"));
alert("is number not a number ? :" + isNaN(1));
The first alert will print true and the second one will return false.
Download
Feel free to download the full source code of this example from my github.