Home > Article > Web Front-end > How to determine whether a specified string is contained in javascript
Judgment method: 1. Use indexOf(), if no matching string is found, return "-1"; 2. Use lastIndexOf() method, if no matching string is found, return "-1"; 3. Use the search() method to retrieve the specified substring in the string; 4. Use the match() method.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Javascript method to determine whether a specified string is included
1. Use indexOf()
The indexOf() method returns the position where a specified string value first appears in the string. If the string value to be retrieved does not appear, the method returns -1.
var str = "123"; console.log(str.indexOf("3") != -1 ); // true
indexOf() method searches from left to right. If you want to search from right to left, you can use the lastIndexOf() method to search.
2. Use the lastIndexOf() method
The lastIndexOf() method can return the last occurrence position of a specified string value. If you specify the second The parameter start searches from back to front at the specified position in a string. Returns -1 if no matching string is found.
The search order of the lastIndexOf() method is from right to left, but its parameters and return value are calculated from left to right according to the subscript of the string, that is, the first character of the string The subscript value is always 0, and the subscript value of the last character is always length-1.
var str = "123"; console.log(str.lastIndexOf("3") != -1 ); // true
3. Use the search() method
The search() method is used to retrieve a specified substring in a string, or to retrieve a match that matches a regular expression substring. If no matching substring is found, -1 is returned.
var str = "123"; console.log(str.search("3") != -1 ); // true
4. Use the match() method
The match() method can retrieve a specified value within a string, or find one or more regular expressions. Match
match() method can find all matching substrings and return them in the form of an array.
var str = "123"; var reg = RegExp(/3/); if(str.match(reg)){ // 包含 }
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to determine whether a specified string is contained in javascript. For more information, please follow other related articles on the PHP Chinese website!