Home >Web Front-end >JS Tutorial >How to determine whether javascript contains a specified string

How to determine whether javascript contains a specified string

青灯夜游
青灯夜游Original
2022-01-18 18:28:2239057browse

Judgment method: 1. Use the indexOf() method to obtain the first occurrence position of the specified string value. If the return value is "-1", it is not included; 2. Use the search() method to retrieve the specified string. If the return value is "-1", it is not included; 3. Use the match() method; 4. Use the test() method, etc.

How to determine whether javascript contains a specified string

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript determines whether the string contains the specified string

Method 1: indexOf() (recommended)

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

Method 2: search()

The search() method is used to retrieve the specified substring in the string, or to retrieve it with a regular expression Matching substring, if no matching substring is found, -1 is returned.

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

Method 3: match()

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

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

Method 4: test()

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

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

Method 5: exec()

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.

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

【Related recommendations: javascript learning tutorial

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

Statement:
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