Home  >  Article  >  Web Front-end  >  Summary of methods to use JS to determine the content contained in a string

Summary of methods to use JS to determine the content contained in a string

php中世界最好的语言
php中世界最好的语言Original
2018-06-01 11:37:532448browse

This time I will bring you a summary of the method of using JS to determine the content contained in a string . What are the precautions for using JS to determine the content contained in a string. The following is a practical case. , let’s take a look.

String object methods

Method 1: indexOf() (recommended)

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

Method 3: search()

 var str = "123"
 console.log(str.search("2") != -1); // true
The search() method is used to retrieve the substring specified in the string, or retrieve the same Regular expression matching substring. If no matching substring is found, -1 is returned.

Methods of RegExp object

##Method 4: test()

 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 a string. Returns true or false.

Method 5: exec()

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

exec() method is used for retrieval Regular expression matching in strings. Returns an array containing the matching results. If no match is found, the return value is null. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps to implement snowflake falling animation in JS


How to implement the port reuse function in Node.Js

The above is the detailed content of Summary of methods to use JS to determine the content contained in a 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