javascript - How to highlight text in a html string without breaking tags? -
problem: given html string, how highlight substring in text, make sure tags untouched?
for example replace substring "brown":
str='<img src="brown fox.jpg" title="the brown fox" /><p>some text containing brown.</p>';
or
str='<p>some <span style="color:brown">text containing brown</span></p>';
how highlight substring brown in text, not inside tags (to avoid breaking tag.
this question surfaced here answer how highlight text using javascript
my solution split string along tags, , replace parts odd in array (in between tags), wonder if there gotchas (one can think of invalid html, should handled prior handling text imho)
var str='<p>some <span style="color:brown">text containing brown</span></p>'; //split along tags var parts = str.split(/[<>]+/); //remove empty parts = parts.filter(function(n){ return n != ""}); (var = 0; < parts.length; i++) { if (i%2 !== 0) //console.log(parts[i]); parts[i] = parts[i].replace("brown", "red whatever"); } console.log(parts);
output
["", "p", "some ", "span style="color:brown"", "text containing red whatever", "/span", "", "/p", ""]
assuming can access dom rather manipulating string directly, can access text of dom node doing
$(selector).text()
assign text variable , manipulate hearts content, call
$(selector).text(variable)
to change text in dom.
Comments
Post a Comment