JavaScript String Methods
- Previous Page JS String
- Next Page JS String Search
String methods help you handle strings.
String methods and properties
Primitive values, such as "Bill Gates", cannot have properties and methods (because they are not objects).
However, through JavaScript, methods and properties can also be used for primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String length
length
The property returns the length of the string:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;
Find a string within a string
indexOf()
The method returns the specified text in the stringFirstIndex of occurrence (position):
Example
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("China");
JavaScript counts positions from zero.
0 is the first position in the string, 1 is the second, 2 is the third ...
lastIndexOf()
The method returns the position of the specified text in the stringFinallyIndex of one occurrence:
Example
var str = "The full name of China is the People's Republic of China."; var pos = str.lastIndexOf("China");
If the text is not found, indexOf()
and lastIndexOf()
Both return -1.
Example
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("USA");
Both methods accept the second parameter as the starting position for the search.
Example
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("China", 18);
lastIndexOf()
The method searches backward (from the end to the beginning), which means: if the second parameter is 50, it will search from position 50 to the start of the string.
Example
var str = "The full name of China is the People's Republic of China."; var pos = str.lastIndexOf("China", 50);
Search for a string within a string
search()
The method searches for a specific value in a string and returns the position of the match:
Example
var str = "The full name of China is the People's Republic of China."; var pos = str.search("locate");
Did you notice that?
Two methods,indexOf()
and search()
, isEqual.
These two methods are not equal. The difference is:
- The search() method cannot set the second starting position parameter.
- The indexOf() method cannot set more powerful search values (regular expressions).
You will learnRegular expressionsLearn these more powerful search values in the chapter.
Extract part of the string
There are three methods to extract part of a string:
- slice(start, end)
- substring(start, end)
- substr(start, length)
slice() method
slice()
Extract a part of the string and return the extracted part in a new string.
This method sets two parameters: the start index (starting position), and the end index (ending position).
This example cuts the segment from position 7 to position 13 in the string:
Example
var str = "Apple, Banana, Mango"; var res = str.slice(7, 13);
The result of res is:
Banana
If any parameter is negative, the counting starts from the end of the string.
This example cuts the segment from position -12 to position -6 in the string:
Example
var str = "Apple, Banana, Mango"; var res = str.slice(-13, -7);
The result of res is:
Banana
If the second parameter is omitted, this method will cut the remaining part of the string:
Example
var res = str.slice(7);
Or count from the end:
Example
var res = str.slice(-13);
Tip:Negative value positions are not applicable to Internet Explorer 8 and earlier versions.
substring() method
substring()
Similar to slice()
.
The difference lies in substring()
Negative indices are not accepted.
Example
var str = "Apple, Banana, Mango"; var res = str.substring(7, 13);
The result of res is:
Banana
If the second parameter is omitted, this substring()
Cuts the remaining part of the string.
substr() method
substr()
Similar to slice()
.
The difference lies in the second parameter, which specifies the part to be extracted.Length.
Example
var str = "Apple, Banana, Mango"; var res = str.substr(7, 6);
The result of res is:
Banana
If the second parameter is omitted, this substr() will cut the remaining part of the string.
Example
var str = "Apple, Banana, Mango"; var res = str.substr(7);
The result of res is:
Banana, Mango
If the first parameter is negative, the position is calculated from the end of the string.
Example
var str = "Apple, Banana, Mango"; var res = str.substr(-5);
The result of res is:
Mango
The second parameter cannot be negative because it defines the length.
Replace the string content
replace
Replace the value specified in the string with another value:
Example
str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3School");
replace
The method does not change the string it calls. It returns a new string.
By default,replace
only the first match is replaced:
Example
str = "Please visit Microsoft and Microsoft!"; var n = str.replace("Microsoft", "W3School");
By default,replace
is case-sensitive. Therefore, it does not match MICROSOFT:
Example
str = "Please visit Microsoft!"; var n = str.replace("MICROSOFT", "W3School");
To perform case-insensitive replacement, use the regular expression /i
(case-insensitive):
Example
str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3School");
Please note that regular expressions do not have quotes.
To replace all matches, use the flag of the regular expression g
Flags (used for global search):
Example
str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "W3School");
You will learn more about JavaScript regular expressions in this chapterRegular expressionscontent.
Convert to uppercase and lowercase
By toUpperCase()
Convert a string to uppercase:
Example
var text1 = "Hello World!"; // string var text2 = text1.toUpperCase(); // text2 is the uppercased version of text1
By toLowerCase()
Convert a string to lowercase:
Example
var text1 = "Hello World!"; // string var text2 = text1.toLowerCase(); // text2 is the lowercased version of text1
concat() method
concat()
Concatenate two or more strings:
Example
var text1 = "Hello"; var text2 = "World"; text3 = text1.concat(" ",text2);
concat()
Methods can be used instead of the addition operator. The following two lines are equivalent:
Example
var text = "Hello" + " " + "World!"; var text = "Hello".concat(" ","World!");
All string methods return a new string. They do not modify the original string.
Formally speaking: strings are immutable: strings cannot be changed, only replaced.
String.trim()
trim
The method removes whitespace characters at both ends of the string:
Example
var str = " Hello World! "; alert(str.trim());
Warning:Internet Explorer 8 or earlier versions do not support trim
method.
To support IE 8, you can use regular expressions in conjunction with the method replace
Method instead:
Example
var str = " Hello World! "; alert(str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''));
You can also use the above replace method to add the trim function to JavaScript String.prototype:
Example
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; var str = " Hello World! "; alert(str.trim());
Extracting string characters
These are two methods to extract characters from a stringSafeMethod:
- charAt(position)
- charCodeAt(position)
charAt() method
charAt()
The method returns the substring at the specified index (position):
Example
var str = "HELLO WORLD"; str.charAt(0); // Returns H
charCodeAt() method
charCodeAt
The method returns the Unicode encoding of the character at the specified index in the string:
Example
var str = "HELLO WORLD"; str.charCodeAt(0); // Returns 72
Property Access
ECMAScript 5 (2009) allows property access for strings [ ]:
Example
var str = "HELLO WORLD"; // Return H
Using property access is a bit unreliable:
- Not applicable to Internet Explorer 7 or earlier versions
- It makes the string look like an array (but it is not)
- If the character is not found,
[ ]
Returnsundefined
andcharAt()
Returns an empty string. - It is read-only.
str[0] = "A"
No error (but it won't work either!)
Example
var str = "HELLO WORLD"; str[0] = "A"; // No error, but it won't work // Return H
Tip:If you want to process the string as an array, you can first convert it to an array.
Convert a string to an array
You can split()
Convert the string to an array:
Example
var txt = "a,b,c,d,e"; // String txt.split(","); // Split using a comma txt.split(" "); // Split using a space txt.split("|"); // Split using a vertical line
If the delimiter is omitted, the returned array will contain the entire string in index [0].
If the delimiter is "", the returned array will be an array of single characters separated by intervals:
Example
var txt = "Hello"; // String txt.split("\""); // Split into characters
Complete String Reference Manual
For a complete reference manual, please visit our full JavaScript String Reference Manual.
This manual includes descriptions and examples of all string properties and methods.
- Previous Page JS String
- Next Page JS String Search