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

How to determine whether a string contains a certain string in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-06 17:26:2124722browse

Javascript method to determine whether a string contains a certain string: 1. Use the [indexOf()] method to return the position where a specified string value first appears in the string; 2. Use The [search()] method is used to retrieve a specified substring in a string.

How to determine whether a string contains a certain string in javascript

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

Javascript method to determine whether a string contains a certain string:

Method 1: indexOf()

var str = "123";
console.log(str.indexOf("3") != -1 );  // true
## 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: search()

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

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

Method 3: match()

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

The match() method can retrieve the specified value within the string, or find one or more A match of regular expressions.

Method 4: test()

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

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

Method 5: exec()

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

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.

Related free learning recommendations: javascript(Video)

The above is the detailed content of How to determine whether a string contains a certain string in javascript. 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