Home >Web Front-end >Front-end Q&A >How to determine whether there is a certain string in a string in es6

How to determine whether there is a certain string in a string in es6

青灯夜游
青灯夜游Original
2023-01-16 17:23:044175browse

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)".

How to determine whether there is a certain string in a string in es6

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!

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