- Поиск и подсветка текста на странице (JavaScript — jQuery)
- 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 — 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
Вот походу и все.
Прошу прощения за неоптимизированный код — вот только что закончил и решил поделится, это только начальная версия
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 |