- Как найти слово в строке JavaScript? Ищем символ в строке. Метод indexOf()
- Приведем примеры поиска слова в строке JavaScript
- JavaScript String search()
- Note
- See Also:
- Syntax
- Parameters
- Return Value
- The Difference Between String search() and String indexOf()
- The Difference Between String search() and String match()
- Regular Expression Search Methods
- Related Pages
- Browser Support
- JavaScript String Search
- Example
- Note
- JavaScript String lastIndexOf()
- Example
- Example
- Example
- Example
- JavaScript String search()
- Examples
- Did You Notice?
- JavaScript String match()
- Examples
- Note
- JavaScript String matchAll()
- Example
- Example
- Example
- Notes
- JavaScript String includes()
- Examples
- Notes
- JavaScript String startsWith()
- Examples
- Notes
- JavaScript String endsWith()
- Examples
- Notes
- Complete String Reference
- String.prototype.search()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Using search()
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
Как найти слово в строке JavaScript? Ищем символ в строке. Метод indexOf()
Для поиска слова, символа или любой другой подстроки в строке в языке программирования JavaScript используют хорошо известный метод indexOf. В результате проверки метод возвращает позицию первого совпадения, если же совпадение по введённому вами символу найдено не будет, будет возвращено -1.
Искомое слово или символ указываются первым параметром. Что касается второго параметра, то он необязателен. Зато с его помощью мы можем передать номер (индекс) символа или буквы, с которого надо начинать поиск. Важный момент: метод indexOf() чувствителен к регистру вводимых вами букв, слов и символов.
Синтаксис метода предельно прост:
строка.indexOf(первый параметр указывает, что ищем, [второй параметр определяет, откуда начинаем поиск]);Приведем примеры поиска слова в строке JavaScript
В примере ниже у нас есть строка 'Я учусь в OTUS', причём мы ищем в строке слово 'учусь'. Метод вернёт нам индекс 2, т. к. именно с этой позиции начинается слово 'учусь' в строке. Тут стоит вспомнить, что индексация (подсчёт позиции) начинается с нуля, а не с единицы.
let str = 'Я учусь в OTUS; console.log(str.indexOf('учусь'));В результате получим следующий вывод:
В очередном примере в строке 'Я учу Java и учу JavaScript в OTUS' давайте найдём слово 'учу', но не первое его вхождение в строку, а второе. Следовательно, начнём поиск с 5-й позиции, указав это вторым параметром.
let str = 'Я учу Java и учу JavaScript в OTUS'; console.log(str.indexOf('учу', 5));Проверка приведёт к возвращению числа 13, т. к. именно с этой позиции начинается второе слово «учу» в нашей строке.
Давайте приведем ещё парочку примеров. В коде ниже, исследуемый нами метод поиска вернёт -1, ведь подстроки 'Go' в нашей строке попросту нет:
let str = 'Я учусь в OTUS'; console.log(str.indexOf('Go'));В принципе, как видите, ничего сложного. Нам вернётся -1 и в случае, если мы будем искать одинаковые слова с разным регистром (OTUS не равно OtuS):
let str = 'Я учусь в OTUS; console.log(str.indexOf(' OtuS'));Вернётся -1 и в последнем примере, ведь после позиции, которую мы выбрали вторым параметром для поиска, совпадения найдены не будут:
let str = 'Я учусь в OTUS'; console.log(str.indexOf('учусь', 7));Проверка приведёт к следующему результату:
Вот и всё, что можно сказать про простейший поиск слов и символов в строке JavaScript. Напоследок стоит упомянуть метод lastIndexOf() , тоже осуществляющий поиск символа, слова или любой подстроки в строке. Разница заключается лишь в том, что этот метод начинает искать с конца строки, а не с начала — в остальном он работает аналогично.
Больше операций по поиску в строке JavaScript, включая дополнительные операции по работе с подстрокой, вы найдёте здесь.
Интересует профессиональный курс по JavaScript-разработке? Переходите по ссылке ниже:
JavaScript String search()
The search() method matches a string against a regular expression ** The search() method returns the index (position) of the first match. The search() method returns -1 if no match is found. The search() method is case sensitive.
Note
See Also:
Syntax
Parameters
Parameter | Description |
searchValue | Required. The search value. A regular expression (or a string that will be converted to a regular expression). |
Return Value
The Difference Between
String search() and String indexOf()
The search() cannot take a start position argument.
The indexOf() method cannot search against a regular expression.
The Difference Between
String search() and String match()
The search() method returns the position of the first match.
The match() method returns an array of matches.
Regular Expression Search Methods
In JavaScript, a regular expression text search, can be done with different methods.
With a pattern as a regular expression, these are the most common methods:
Example | Description |
---|---|
text.match(pattern) | The String method match() |
text.search(pattern) | The String method search() |
pattern.exec(text) | The RexExp method exec() |
pattern.test(text) | The RegExp method test() |
Related Pages
Browser Support
search() is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
JavaScript String Search
The indexOf() method returns the index (position) the first occurrence of a string in a string:
Example
Note
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third, .
JavaScript String lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
Example
Both indexOf() , and lastIndexOf() return -1 if the text is not found:
Example
Both methods accept a second parameter as the starting position for the search:
Example
The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15 , the search starts at position 15, and searches to the beginning of the string.
Example
JavaScript String search()
The search() method searches a string for a string (or a regular expression) and returns the position of the match:
Examples
Did You Notice?
The two methods, indexOf() and search() , are equal?
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
- The search() method cannot take a second start position argument.
- The indexOf() method cannot take powerful search values (regular expressions).
You will learn more about regular expressions in a later chapter.
JavaScript String match()
The match() method returns an array containing the results of matching a string against a string (or a regular expression).
Examples
Perform a global search for "ain":
Perform a global, case-insensitive search for "ain":
Note
If a regular expression does not include the g modifier (global search), match() will return only the first match in the string.
Read more about regular expressions in the chapter JS RegExp.
JavaScript String matchAll()
The matchAll() method returns an iterator containing the results of matching a string against a string (or a regular expression).
Example
If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.
Example
If you want to search case insensitive, the insensitive flag (i) must be set:
Example
Notes
matchAll() does not work in Internet Explorer.
JavaScript String includes()
The includes() method returns true if a string contains a specified value.
Otherwise it returns false .
Examples
Check if a string includes "world":
Check if a string includes "world". Start at position 12:
Notes
includes() is case sensitive.
includes() is not supported in Internet Explorer.
JavaScript String startsWith()
The startsWith() method returns true if a string begins with a specified value.
Otherwise it returns false :
Examples
A start position for the search can be specified:
Notes
startsWith() is case sensitive.
startsWith() is not supported in Internet Explorer.
JavaScript String endsWith()
The endsWith() method returns true if a string ends with a specified value.
Otherwise it returns false :
Examples
Check if a string ends with "Doe":
Check if the 11 first characters of a string ends with "world":
Notes
endsWith() is case sensitive.
endsWith() is not supported in Internet Explorer.
Complete String Reference
For a complete String reference, go to our:
The reference contains descriptions and examples of all string properties and methods.
String.prototype.search()
The search() method executes a search for a match between a regular expression and this String object.
Try it
Syntax
Parameters
A regular expression object, or any object that has a Symbol.search method.
If regexp is not a RegExp object and does not have a Symbol.search method, it is implicitly converted to a RegExp by using new RegExp(regexp) .
Return value
The index of the first match between the regular expression and the given string, or -1 if no match was found.
Description
The implementation of String.prototype.search() itself is very simple — it simply calls the Symbol.search method of the argument with the string as the first parameter. The actual implementation comes from RegExp.prototype[@@search]() .
The g flag of regexp has no effect on the search() result, and the search always happens as if the regex's lastIndex is 0. For more information on the behavior of search() , see RegExp.prototype[@@search]() .
When you want to know whether a pattern is found, and also know its index within a string, use search() .
- If you only want to know if it exists, use the RegExp.prototype.test() method, which returns a boolean.
- If you need the content of the matched text, use match() or RegExp.prototype.exec() .
Examples
Using search()
The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search ( -1 ).
const str = "hey JudE"; const re = /[A-Z]/; const reDot = /[.]/; console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J" console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation
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 5, 2023 by MDN contributors.
Your blueprint for a better internet.