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

Поиск в строке JavaScript. Работа с подстрокой

В предыдущей статье мы начали тему работы со строками в JavaScript. В этом материале вы узнаете, как выполнять поиск в строке, как работать с подстрокой, как извлекать часть строки и т. д.

Поиск строки в строке в JavaScript

С помощью метода IndexOf() можно вернуть индекс первого вхождения заданного текста в строку:

 
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate");

В нашем случае происходит подсчёт позиции с нуля. При этом: 1) 0 — первая позиция в строке, 2) 1 — вторая, 3) 2 — третья.

Идём дальше. Функция LastIndexOf() в JavaScript вернёт индекс последнего вхождения:

 
var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate");

Оба этих метода принимают 2-й параметр в виде начальной позиции для поиска:

 
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate",15);

Стоит упомянуть и функцию Search() — она выполняет поиск строки для заданного значения, возвращая позицию совпадения:

 
var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate");

Метод slice () в JavaScript

Функция slice() извлечёт часть строки и вернёт извлечённую часть в новой строке. Метод способен принимать два параметра: начальный индекс (это положение) и конечный индекс (речь идёт о позиции).

К примеру, давайте нарежем часть строки из позиции 7 в положение 13:

 
var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13);

В нашем случае результатом будет:

Если параметр будет иметь отрицательное значение, то позиция будет учитываться с конца строки. Например:

 
var str = "Apple, Banana, Kiwi"; var res = str.slice(-12, -6);

Кстати, если 2-й параметр опустить, то метод сделает срез оставшейся части строки:

То же самое получим, выполнив срез с конца:

Остаётся лишь добавить, что отрицательные позиции не функционируют в Internet Explorer 8 и других, более ранних версиях.

Метод подстроки в JavaScript

Подстрока в JavaScript аналогична срезу с той разницей, что подстрока не способна принимать отрицательные индексы:

 
var str = "Apple, Banana, Kiwi"; var res = str.substring(7, 13);

В качестве результата опять получим «Banana».

Если же мы опустим 2-й параметр, то подстрока разрежет оставшуюся часть строки.

Метод substr () в JavaScript

Строковый метод substr() похож на slice() с той разницей, что 2-й параметр показывает длину извлечённой детали.

 
var str = "Apple, Banana, Kiwi"; var res = str.substr(7, 6);

Мы можем опустить 2-й параметр — тогда строковый метод substr() разрежет оставшуюся часть строки.

 
var str = "Apple, Banana, Kiwi"; var res = str.substr(7);

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

 
var str = "Apple, Banana, Kiwi"; var res = str.substr(-4);

Меняем содержимое строки в JavaScript

Строковый метод Replace() позволит заменить указанное значение иным значением в строке:

 
str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3Schools");

Результат: Please visit W3Schools!

Обратите внимание, что метод Replace() не изменит строку, в которой вызывается, а возвратит новую.

В следующем примере функция Replace() меняет лишь первое совпадение:

 
str = "Please visit Microsoft and Microsoft!"; var n = str.replace("Microsoft", "W3Schools");

Итог: Please visit W3Schools and Microsoft!

Кстати, по умолчанию Replace() учитывает регистр. Написав MICROSOFT, мы увидим, что функция работать не будет: Пример

 
str = "Please visit Microsoft!"; var n = str.replace("MICROSOFT", "W3Schools");

Но мы можем заменить регистр без его учёта, если воспользуемся регулярным выражением с пометкой " i ":

 
str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3Schools");

Результат: Please visit W3Schools!

Здесь стоит заметить, что регулярные выражения надо писать без кавычек.

Если желаете заменить все совпадения, воспользуйтесь регулярным выражением с флагом /g:

 
str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "W3Schools");

Тут получим следующее: Please visit W3Schools and W3Schools!

Извлекаем строковые символы в JavaScript

Есть 2 безопасных строковых функции для извлечения строковых символов: • charCodeAt (позиция); • charAt (позиция).

Функция charAt() возвратит символ по указанному нами индексу (позиции) в строке:

 
var str = "HELLO WORLD"; str.charAt(0);

Что касается метода charCodeAt(), то он вернёт Юникод символа по указанному нами индексу:

 
var str = "HELLO WORLD"; str.charCodeAt(0); // вернёт 72

Что ж, на этом всё, удачного вам кодинга!

Интересует профессиональный курс по 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.

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.

Источник

Читайте также:  Java http response http header
Оцените статью