- 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 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
- Поиск и подсветка текста на странице (JavaScript — jQuery)
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.
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.
Поиск и подсветка текста на странице (JavaScript — jQuery)
Нужен был поиск на страничке, точнее в тексте, не серверный, а обычный. То есть — загрузил страничку где много текста, читаешь, и при надобности ищешь. Порылся в интернете и, к сожалению, готово варианта (с переходом между словами и прокруткой странички) не нашел, хотя в реализации нету ничего сложного — или плохо искал, или никому не надо было.
Вот как раз заканчиваю — решил поделиться первым вариантом.
Само собой используется библиотека jQuery.
За основу я взял статейку jQuery – подсветка слов в тексте или HTML отсюда (их пример). Как подключить к страничке скрипт там описано.
буду использовать ниже «слово» = «словосочетание» = «словосочетание букв и\или символов».
Теперь начнем расширять функционал:
кнопки поиска, выделение следующего слова и предыдущего, и скролл странички к выделенному слову
jQuery.fn.selectHighlight = function(number) < return this.find("span.highlight:eq("+number+")").addClass('selectHighlight').end(); >;
2) в стиль прописываем отображение выделяемого слова и меняем стиль подсветки для себя
.highlight < background-color: gray; color: white >.selectHighlight
3)Создаем кнопки и поле ввода
4)приписываем кнопкам действия
копируем код:
(ниже опишу для чего эта функция)
var search_number = 0; //индекс конкретного сочетания из найденных var search_count = 0; //количество найденных сочетаний //search - поиск слова по нажатию на кнопку "search_button" $('#search_button').click(function() < $('#text').removeHighlight(); txt = $('#search_text').val(); if (txt == '') return; $('#text').highlight(txt); search_count = $('#text span.highlight').size() - 1; search_number = 0; $('#text').selectHighlight(search_number); //выделяем первое слово из найденных scroll_to_word(); //скролим страничку к выделяемому слову >); //clear - очистка выделения по нажатию на кнопку "clear_button" $('#clear_button').click(function() < $('#text').removeHighlight(); >); //prev_search - выделяем предыдущие слово из найденных и скролим страничку к нему $('#prev_search').click(function() < if (search_number == 0) return; $('#text .selectHighlight').removeClass('selectHighlight'); search_number--; $('#text').selectHighlight(search_number); scroll_to_word(); >); //next_search - выделяем следующее слово из найденных и скролим страничку к нему $('#next_search').click(function() < if (search_number == search_count) return; $('#text .selectHighlight').removeClass('selectHighlight'); search_number++; $('#text').selectHighlight(search_number); scroll_to_word(); >);
5)
function scroll_to_word() <. >— функция скрола (перемотки) странички к нужному нам слову
ну вообще делается очень легко с помощью простого плагина jqueryscrollto, который берем отсюда, и ищем по классу .highlight и номером eq(‘+search_number +’) ( search_number — смотрим в список глобальных переменных скрипта).
jQuery('#content').scrollTo('.highlight('+search_number +')');
Но мне пришлось использовать этот набор плагинов (jqwidgets), так как был нужен собственный скрол для странички а не браузерный, поэтому я воспользовался их API:
scrollTo Method
Scroll to specific position.
Code examples
Invoke the scrollTo method.
$('#jqxPanel').jqxPanel('scrollTo', 10, 20);
Demo
Вот походу и все.
Прошу прощения за неоптимизированный код — вот только что закончил и решил поделится, это только начальная версия