Home > Web Front-end > JS Tutorial > body text

How to determine whether a string contains another string in JS

不言
Release: 2018-05-05 16:39:39
Original
4160 people have browsed it

This article brings you five ways to determine whether a string contains another string in JS, including string object methods, match() methods, RegExp object methods, test() methods, and exec() Method, please refer to this article for details.

String object method

Method 1: indexOf() (recommended)

 var str = "123"
 console.log(str.indexOf("2") != -1); // true
Copy after login

The indexOf() method returns the position of the first occurrence of a specified string value in a string. If the string value to be retrieved does not appear, the method returns -1.

Method 2: match()

 var str = "123"
var reg = RegExp(/3/);
if(str.match(reg)){
  //包含;
}
Copy after login

match() method can be used in characters Searches a specified value within a string, or finds a match for one or more regular expressions.

Method 3: search()

 var str = "123"
 console.log(str.search("2") != -1); // true
Copy after login

search() method is used for retrieval A specified substring in a string, or retrieves a substring that matches a regular expression. If no matching substring is found, -1 is returned.

RegExp object methods

Method 4: test()

 var str = "123"
var reg = RegExp(/3/);
 console.log(reg.test(str) != -1); // true
Copy after login

#test() method is used to retrieve the value specified in a string. Returns true or false.

Method 5: exec()

 var str = "123"
var reg = RegExp(/3/);
if(reg.exec(str)){
  //包含;
}
Copy after login

##exec () method is used to retrieve matches of a regular expression in a string. Returns an array containing the matching results. If no match is found, the return value is null.

Related recommendations:


Two methods to determine whether the text box is empty in js_javascript skills

Analysis of the method of judging null in JS

The above is the detailed content of How to determine whether a string contains another string in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!