Javascript наличие символа в строке

How to check if a string contains a substring in JavaScript

There are multiple ways to check if a string contains a substring in JavaScript. You can use either String.includes() , String.indexOf() , String.search() , String.match() , regular expressions, or 3rd-party library like Lodash.

The String.includes() provides the most simple and popular way to check if a string contains a substring in modern JavaScript. It was introduced in ES6 and works in all modern browsers except Internet Explorer. The String.includes() method returns true if the string contains the specified substring. Otherwise, it returns false . Here is an example:

let str = 'MongoDB, Express, React, Node' str.includes('MongoDB') //true str.includes('Java') //false str.includes('Node') //true 

Note that includes() is case-sensitive and accepts an optional second parameter, an integer, which indicates the position where to start searching for.

let str = 'MongoDB, Express, React, Node' str.includes('express') // false (Due to case-sensitive) str.includes('React', 5) // true 

The String.indexOf() method returns the index of the first occurrence of the substring. If the string does not contain the given substring, it returns -1 . The indexOf() method is case-sensitive and accepts two parameters. The first parameter is the substring to search for, and the second optional parameter is the index to start the search from (the default index is 0 ).

let str = 'MongoDB, Express, React, Node' str.indexOf('MongoDB') !== -1 // true str.indexOf('Java') !== -1 // false str.indexOf('Node', 5) !== -1 // true 

The String.search() method searches the position of the substring in a string and returns the position of the match. The search value can be a string or a regular expression. It returns -1 if no match is found.

let str = 'MongoDB, Express, React, Node' str.search('MongoDB') !== -1 // true str.search('Java') !== -1 // false str.search(/node/i) !== -1 // true where i is the case insensitive modifier 

The String.match() method accepts a regular expression as a parameter and searches the string for a match. If it finds the matches, it returns an object, and null if no match is found.

let str = 'MongoDB, Express, React, Node' str.match(/MongoDB/) // ['MongoDB', index: 0, input: 'MongoDB, Express, React, Node', groups: undefined] str.match(/Java/) // null str.match(/MongoDB/g) !== null // true str.match(/Java/g) !== null // false str.match(/node/i) !== null // true where i is the case insensitive modifier 

The RegExp.test() method executes a search for a match between a regular expression and a specified string. It returns true if it finds a match. Otherwise, it returns false .

let str = 'MongoDB, Express, React, Node' const exp = new RegExp('MongoDB', 'g') exp.test(str) // true /Java/g.test(str) // false /node/i.test(str) // true where i is the case insensitive modifier 

Lodash is a third-party library that provides _.includes() method to check the presence of a substring in a string. This method returns true if a match is found, otherwise, false .

let str = 'MongoDB, Express, React, Node' _.includes(str, 'MongoDB') // true _.includes(str, 'Java') // false _.includes(str, 'Node') // true 

You might also like.

Источник

String.prototype.includes()

The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.

Try it

Syntax

includes(searchString) includes(searchString, position) 

Parameters

A string to be searched for within str . Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes includes() to search for the string «undefined» , which is rarely what you want.

The position within the string at which to begin searching for searchString . (Defaults to 0 .)

Return value

true if the search string is found anywhere within the given string, including when searchString is an empty string; otherwise, false .

Exceptions

Description

This method lets you determine whether or not a string includes another string.

Case-sensitivity

The includes() method is case sensitive. For example, the following expression returns false :

"Blue Whale".includes("blue"); // returns false 

You can work around this constraint by transforming both the original string and the search string to all lowercase:

"Blue Whale".toLowerCase().includes("blue"); // returns true 

Examples

Using includes()

const str = "To be, or not to be, that is the question."; console.log(str.includes("To be")); // true console.log(str.includes("question")); // true console.log(str.includes("nonexistent")); // false console.log(str.includes("To be", 1)); // false console.log(str.includes("TO BE")); // false console.log(str.includes("")); // true 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 6, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

String.prototype.indexOf()

The indexOf() method of String values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.

Try it

Syntax

indexOf(searchString) indexOf(searchString, position) 

Parameters

Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string «undefined» , which is rarely what you want.

The method returns the index of the first occurrence of the specified substring at a position greater than or equal to position , which defaults to 0 . If position is greater than the length of the calling string, the method doesn’t search the calling string at all. If position is less than zero, the method behaves as it would if position were 0 .

  • ‘hello world hello’.indexOf(‘o’, -5) returns 4 — because it causes the method to behave as if the second argument were 0 , and the first occurrence of o at a position greater or equal to 0 is at position 4 .
  • ‘hello world hello’.indexOf(‘world’, 12) returns -1 — because, while it’s true the substring world occurs at index 6 , that position is not greater than or equal to 12 .
  • ‘hello world hello’.indexOf(‘o’, 99) returns -1 — because 99 is greater than the length of hello world hello , which causes the method to not search the string at all.

Return value

The index of the first occurrence of searchString found, or -1 if not found.

Return value when using an empty search string

Searching for an empty search string produces strange results. With no second argument, or with a second argument whose value is less than the calling string’s length, the return value is the same as the value of the second argument:

"hello world".indexOf(""); // returns 0 "hello world".indexOf("", 0); // returns 0 "hello world".indexOf("", 3); // returns 3 "hello world".indexOf("", 8); // returns 8 

However, with a second argument whose value is greater than or equal to the string’s length, the return value is the string’s length:

"hello world".indexOf("", 11); // returns 11 "hello world".indexOf("", 13); // returns 11 "hello world".indexOf("", 22); // returns 11 

In the former instance, the method behaves as if it found an empty string just after the position specified in the second argument. In the latter instance, the method behaves as if it found an empty string at the end of the calling string.

Description

Strings are zero-indexed: The index of a string’s first character is 0 , and the index of a string’s last character is the length of the string minus 1.

"Blue Whale".indexOf("Blue"); // returns 0 "Blue Whale".indexOf("Blute"); // returns -1 "Blue Whale".indexOf("Whale", 0); // returns 5 "Blue Whale".indexOf("Whale", 5); // returns 5 "Blue Whale".indexOf("Whale", 7); // returns -1 "Blue Whale".indexOf(""); // returns 0 "Blue Whale".indexOf("", 9); // returns 9 "Blue Whale".indexOf("", 10); // returns 10 "Blue Whale".indexOf("", 11); // returns 10 

The indexOf() method is case sensitive. For example, the following expression returns -1 :

"Blue Whale".indexOf("blue"); // returns -1 

Checking occurrences

When checking if a specific substring occurs within a string, the correct way to check is test whether the return value is -1 :

"Blue Whale".indexOf("Blue") !== -1; // true; found 'Blue' in 'Blue Whale' "Blue Whale".indexOf("Bloe") !== -1; // false; no 'Bloe' in 'Blue Whale' 

Examples

Using indexOf()

The following example uses indexOf() to locate substrings in the string «Brave new world» .

const str = "Brave new world"; console.log(str.indexOf("w")); // 8 console.log(str.indexOf("new")); // 6 

indexOf() and case-sensitivity

The following example defines two string variables.

The variables contain the same string, except that the second string contains uppercase letters. The first console.log() method displays 19 . But because the indexOf() method is case sensitive, the string «cheddar» is not found in myCapString , so the second console.log() method displays -1 .

const myString = "brie, pepper jack, cheddar"; const myCapString = "Brie, Pepper Jack, Cheddar"; console.log(myString.indexOf("cheddar")); // 19 console.log(myCapString.indexOf("cheddar")); // -1 

Using indexOf() to count occurrences of a letter in a string

The following example sets count to the number of occurrences of the letter e in the string str :

const str = "To be, or not to be, that is the question."; let count = 0; let position = str.indexOf("e"); while (position !== -1)  count++; position = str.indexOf("e", position + 1); > console.log(count); // 4 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 28, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Читайте также:  Таблицы
Оцените статью