D
D
display: block2016-03-03 18:35:14
JavaScript
display: block, 2016-03-03 18:35:14

How to properly mark text with regular expressions?

The problem is register saving. "POSTER" was replaced by "Poster". I saw my mistake (I insert the line exactly from the address to the place where I went through the regular expression already in the search results). Where to dig so that the text is marked, but the original case of the original text is preserved?

HTML

<h3>Адресная строка:</h3>
<div class="url">https://toster.ru/results.html&search=остер</div>
<h3>Результаты поиска:</h3>
<div class="search-res">тостер ПоСтеР комПОСТер</div>
<div class="search-res">Григорий Остер и клостЕР</div>

css
.search-mark{
  background:#8BC34A;
}

JS
var urlSearchResult = $('.url').text().replace(/(https?:\/\/toster\.ru\/results\.html\&search=)(.*)/ig,'$2');

var regSearch = new RegExp(urlSearchResult, 'ig');

var searchSpan = "<span class='search-mark'>"+urlSearchResult+"</span>";

var resCount = $(".search-res").length;

for(var i = 0; i <= resCount - 1; i++){
  var searchInsert = $('.search-res').eq(i).text().replace(regSearch, searchSpan);
  $('.search-res').eq(i).html(searchInsert);
};

At the output
f220fc6811714f899bcb643ee17b71af.png
codepen.io/anon/pen/pyJGEG

UPD
Almost solved the problem, but I'll have to set it aside for a couple of hours.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2016-03-03
@qork

This is how it seems to work:

var searchStr = 'остер'

var source = document.querySelector('#source')
var result = document.querySelector('#result')
var regexp = new RegExp('('+searchStr+')', "gim");

result.innerHTML = source.innerHTML.replace(regexp, "<span>$1</span>");
Demo: https://jsfiddle.net/9c0n02Lp/
But there is a fly in the ointment:
https://developer.mozilla.org/ru/docs/Web/JavaScri...
Although almost all browsers support it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question