Javascript find text function

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.

Читайте также:  Команда для очистки консоли в python

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.

Источник

Window: find() method

Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Note: Support for Window.find() might change in future versions of Gecko. See Webkit bug 672395.

The Window.find() method finds a string in a window sequentially.

Syntax

find(aString, aCaseSensitive, aBackwards, aWrapAround, aWholeWord, aSearchInFrames, aShowDialog) 

Parameters

The text string for which to search.

A boolean value. If true , specifies a case-sensitive search.

A boolean value. If true , specifies a backward search.

A boolean value. If true , specifies a wrap around search.

A boolean value. If true , specifies a whole word search. This is not implemented; see Firefox bug 481513.

A boolean value. If true , specifies a search in frames.

Return value

true if the string is found; otherwise, false .

Examples

JavaScript

function findString(text)  document.querySelector("#output").textContent = `String found? $window.find( text, )>`; > 

HTML

p>Apples, Bananas, and Oranges.p> button type="button" onClick='findString("Apples")'>Search for Applesbutton> button type="button" onClick='findString("Bananas")'> Search for Bananas button> button type="button" onClick='findString("Orange")'>Search for Orangebutton> p id="output">p> 

Result

Notes

In some browsers, Window.find() selects (highlights) the found content on the site.

Specifications

This is not part of any specification.

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Как найти слово в строке 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()

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

Источник

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