This article brings you five methods for judging whether a string contains another string in JS. There are the method of the string
object, the match()
method, the method of the RegExp
object, and the `test()` Method, exec()
method, please refer to the following article for specific details:
Methods of String object:
var str = "123"
console.log(str.indexOf("2") != -1); // true
The indexOf()
method can return the position of the first occurrence of a specified string value in the string. If the string value to be retrieved does not appear, the method returns -1
.
var str = "123"
var reg = RegExp(/3/);
if(str.match(reg)){
//Include;
}
The match()
method can retrieve a specified value within a string, or find a match of one or more regular expressions.
var str = "123"
console.log(str.search("2") != -1); // true
The search()
method is used to retrieve the specified substring in the string, or retrieve the substring that matches the regular expression. If no matching substring is found, -1
is returned.
Methods of RegExp object:
var str = "123"
var reg = RegExp(/3/);
console.log(reg.test(str) != -1); // true
The test()
method is used to retrieve the value specified in the string. Return true
or false
.
var str = "123"
var reg = RegExp(/3/);
if(reg.exec(str)){
//Include;
}
The exec()
method is used to retrieve the match of the regular expression in the string. Returns an array in which the matching results are stored. If no match is found, the return value is null
.