String in JavaScript
- The String Object
-
JavaScript String object allows us to store a sequence of characters.
It can be created using :
-
String Literal
var city=“Bhopal”;
-
String Constructor
var city=new String(“Bhopal”);
Using String Methods/Propertiess
length: Returns the length of the string
var str=“Bhopal”
alert(str.length();
//Output:
6
charAt(index): Returns the character at the given
var str=“Bhopal”
alert(str.charAt(4));
//Output:
a
charCodeAt(index):Returns the unicode(ascii) of the character at specified index
var str=“Bhopal”
alert(str.charCodeAt(4));
//Output:
97
indexOf(text):Returns the index of given text in the calling string.
var str=“Programming”
alert(str.indexOf (“ram”));
//Output:
4
lastIndexOf(text): Returns the last index of given text in the calling string.
var str=“Welcome User”
alert(str.indexOf (“e”));
//Output:
10
replace(string,string):
Replaces first occurrence of given string with new string.
var s1=“Welcome User”
var s2=s1.replace(“User”,”Nishant”);
alert(s2);
//Output:
Welcome Nishantsubstr(start,lenght):
Returns length number of characters from start position.
var s1=“Programming”
var s2=s1.substr(3,4);
alert(s2);
//Output:
gram