Home>Article>Web Front-end> How to determine whether there is a certain string in a string in es6
Judgment method: 1. Use includes(), the syntax "str.includes(searchString[, position])"; 2. Use indexOf(), the syntax "str.indexOf(substring)", if it returns " -1" is not available; 3. Use test(), match() or search() with regular expression search, syntax "exp.test(str)", "str.match(exp)".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 Method to determine whether a string contains a substring
Method 1: Use the includes() function
ES6 strings have a new includes method, which we can use to determine whether it contains substrings.
str.includes(searchString[, position])
searchString: query substring
position: optional, the position to start searching, the default is 0
'Blue Whale'.includes('Blue'); // returns true 'Blue Whale'.includes('blue'); // returns false
It should be noted that the includes method is case-sensitive.
For browsers that do not support es6, you can add es6-shim, such as:
require('es6-shim')
Method 2: Use the indexOf() function
indexOf This is a method we commonly use to determine whether it contains a substring. If a substring is contained, returns the index of the substring, otherwise returns -1.
var string = "foo", substring = "oo"; if(string.indexOf(substring) == -1) { console.log("不包含子字符串") } else { console.log("包含子字符串") }
Method 3: Using regular expressions
There are three ways to use regular expressions: test, match, search
1, test
var string = "foo", exp = /oo/; var result = exp.test(string);
test returns a Boolean value. Returns true if exists, false otherwise.
Note that the test function caller is a regular expression.
2, match
var string = "foo", exp = /oo/; var result = string.match(exp); console.log(result);
Output result:
["oo", index: 1, input: "foo"]
The caller is a string, if matched, an array is returned, including the matched content: regular expression, index and input.
3. search
var string = "foo", exp = /oo/; var result = string.search(exp);
returns the index of the searched substring. If the search cannot be performed, -1 will be returned
[Related recommendations:javascript video tutorial、web front end】
The above is the detailed content of How to determine whether there is a certain string in a string in es6. For more information, please follow other related articles on the PHP Chinese website!