Javascript 2
Javascript 2
String Length
The length property returns the length of a string:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
//returns 26
indexOf()
The indexOf() method returns the index of (the position of) the first occurrence
of a specified text in a string: if not found returns -1.
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
//returns 7
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate",15);
//returns 21
lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a
specified text in a string: if not found returns -1.
Example:
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
//returns 21
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate",20);
//returns 7
substring(start, end)
substring() extracts a part of a string and returns the extracted part in a new
string. substring() cannot accept negative indexes.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
//retuns Banana
substr()
substr() is similar to substring(). The difference is that the second parameter
specifies the length of the extracted part.
Example:
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
//returns Banana
toLowerCase()
Converts a string to lowercase.
toUpperCase()
Converts a string to uppercase.
trim()
The trim() method removes whitespace from both sides of a string.
Example:
var str = myTrim(" Hello World! ");
alert(str);
More Methods
Method Description
charAt() Returns the character at the specified index (position)
endsWith() Checks whether a string ends with specified string/characters
includes() Checks whether a string contains the specified
string/characters
indexOf() Returns the position of the first found occurrence of a
specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a
specified value in a string
repeat() Returns a new string with a specified number of copies of an
existing string. Syntax :string.repeat(count)
replace() Searches a string for a specified value, or a regular
expression, and returns a new string where the specified
values are replaced. Syntax:
string.replace(searchvalue, newvalue)
startsWith() Checks whether a string begins with specified characters
substr() Extracts the characters from a string, beginning at a specified
start position, and through the specified number of character
substring() Extracts the characters from a string, between two specified
indices
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string