Проверка подстроки в строке javascript

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.
Читайте также:  Основы разработки на php

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.

Источник

JavaScript: Как проверить, содержит ли строка подстроку

Обычной операцией во многих языках программирования является проверка, содержит ли строка другую строку. Хотя это простая и распространенная задача, имена методов часто различаются в разных языках программирования. Например, вот небольшой пример методов, используемых для достижения этого на разных языках:

  1. Java: String.contains() , String.indexOf() и т.д.
  2. Python: оператор in , String.index() , String.find()
  3. Go: strings.Contains()
  4. Ruby: string.include?

Смысл должен быть понятен. Есть миллион способов сделать это, и кажется, что каждый язык реализует это по-своему.

В любом случае, давайте посмотрим, как можно проверить, содержит ли строка подстроку в JavaScript.

Первые два метода, показанные ниже, также работают с массивами, которые сообщают вам, содержит ли массив заданное значение (или его индекс). Помните об этом при чтении статьи, так как она, вероятно, поможет вам в подобных случаях.

String.includes()

Этот метод был введен в ES6 и обычно является предпочтительным методом для простых случаев использования. Если все, что вам нужно сделать, это получить логическое значение, указывающее, находится ли подстрока в другой строке, то это то, что вы хотите использовать.

> let str = 'stackabuse'; > let substr = 'stack'; > str.includes(substr); true 

Как видите, возвращается логическое значение, поскольку строка «stack» является подстрокой «stackabuse».

Это поиск с учетом регистра, поэтому следующее не будет соответствовать подстроке:

> let str = 'StackAbuse'; > let substr = 'stack'; > str.includes(substr); false 

Хотя этого достаточно для большинства случаев использования, метод includes() также предоставляет другой вариант, который может быть полезен для вас. Может быть предоставлен второй аргумент, который сообщает методу, с какого индекса начинать поиск. Поэтому, если вы знаете, что подстрока не содержится в первых 50 символах (или вы просто не хотите, чтобы она соответствовала этим символам), то вы можете использовать метод, подобный следующему:

Смещение ниже 0 просто начинает поиск с индекса 0, а смещение больше, чем string.length , возвращает false , поскольку поиск начинается с string.length .

String.indexOf()

Метод String.indexOf() очень похож на includes() (и его также можно использовать в polyfill includes() ), но единственное отличие — это возвращаемое значение. Вместо того, чтобы возвращать логическое значение, указывающее наличие подстроки, он фактически возвращает индексное местоположение подстроки, или -1, если его нет.

> let str = 'stackabuse'; > let substr = 'abuse'; > str.indexOf(substr); 5 > str.indexOf('apple'); -1

Как видите, этот метод возвращает позицию индекса подстроки, начинающуюся с на 0, и -1, если подстрока не была найдена.

Как и метод includes() , indexOf() чувствителен к регистру и также поддерживает параметр смещения:

> let str = 'StackAbuse'; > let substr = 'abuse'; > str.indexOf(substr); -1 > str.indexOf('Abu', 3); 5 > str.indexOf('Abu', 6); -1 

Этот метод полезен, когда вам нужно знать точное местоположение подстроки, однако он не так чист, когда просто используется как логическое значение:

let str = 'stackabuse'; let substr = 'stack'; if (str.indexOf(substr) > -1)

В таких случаях вы должны использовать метод includes() , поскольку он более подвержен ошибкам.

Regex

Одним из наиболее полезных и мощных способов проверки подстроки является использование регулярных выражений. Использование регулярных выражений для такой задачи дает вам гораздо больше гибкости, чем в предыдущих методах, где вы можете проверять только постоянную строку. Несмотря на то, что регулярное выражение является слишком большой темой, чтобы полностью охватить здесь, мы можем по крайней мере взглянуть на некоторые полезные функции для нашего варианта использования.

Проверка на наличие подстрок в строке с регулярным выражением может быть выполнена с помощью метода RegExp.test() :

> let str = 'stackabuse'; > /stack/.test(str); true 

В отличие от двух предыдущих методов, теперь мы можем выполнять поиск без учета регистра с флагом i :

> let str = 'StackAbuse'; > /stack/i.test(str); true 

В качестве более сложного примера, скажем, вы хотите увидеть, содержит ли строка почтовый индекс (5-значный почтовый индекс), но вам не важно, какой почтовый индекс находится в строке. Такую проблему нельзя решить с помощью includes() или indexOf() . Но с помощью регулярных выражений мы можем легко проверить это:

> let str = 'My zip code is 90210'; > /\d/.test(str); true > str = 'My address is 123 Fake St.'; > /\d/.test(str); false 

Не смотря на то что JavaScript не такой быстрый как например C, в некоторых случаях время выполнения скрипта может быть критичным. В этом случае RegEx лучше заменить на более простой и легковесный метод includes() .

Источник

Оцените статью