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

How to check if a string contains a certain substring in javascript

青灯夜游
Release: 2023-01-05 16:12:03
Original
5613 people have browsed it

Methods for javascript to check whether it contains a certain string: 1. Check through the indexOf() method; 2. Check using the search() method; 3. Check using the match() method; 4. Use test() Check with regular expressions; 5. Use exec() with regular expressions to check.

How to check if a string contains a certain substring in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

String object methods

Method 1: indexOf() (Recommended)

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

The indexOf() method returns 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: search()

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

The search() method is used to retrieve the specified substring in the string, or to retrieve the substring that matches the regular expression. substring. If no matching substring is found, -1 is returned.

Method 3: match()

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

The match() method can retrieve a specified value within a string, or find a match for one or more regular expressions .

RegExp object method

Method 4: test()

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

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

Method 5: exec()

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

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

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to check if a string contains a certain substring in javascript. 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 [email protected]
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!