Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap all instances of word in tag?

If I have a div containing words, like so:

<div class="content">
    In condimentum facilisis porta. Sed nec diam eu diam mattis porta viverra.
</div>

How can I find every instance of a word, say porta, and wrap it with a tag, so that it becomes:

<div class="content">
    In condimentum facilisis <span class="highlight">porta</span>. Sed nec diam eu diam mattis <span class="highlight">porta</span> viverra.
</div>

I've looked at various examples, and I think this is along the right lines:

var elem = $(".content");
elem.text(elem.text().replace("porta", "######"));

But that fails every now and then, and doesn't replace every instance. I also want to stay away from using REGEX, as it's way too cumbersome and shouldn't be used.

like image 368
Charlie Avatar asked Jan 29 '26 19:01

Charlie


2 Answers

try:

$('.content').html($('.content').html().replace(/(porta)/g,'<span class="highlight">$1</span>'));

See: Demo jsFiddle

like image 133
Sudhir Bastakoti Avatar answered Feb 01 '26 14:02

Sudhir Bastakoti


There are various cases where wrapping a word in an element becomes difficult. The trivial case is where you have simple text content:

<div>foo bar foo</div>

Then wrapping "foo" in a B element can be like:

div.innerHTML = div.textContent.replace(/(foo)/g,'<b>$1<\/b>');

However, life is more complex if you have content like:

<div>foo bar <span>foo</span></div>

where the above will remove the span (and any other element inside the div). You can deal with that by iterating over the child elements rather than using textContent (or innerText as appropriate).

There are also cases like:

<div>foo bar <span>f</span>oo</div>

You may also need to deal with word boundaries. Should "foo" be matched anywhere, or only as a whole word? Given

<div>myfoo bar foo</div>

should myfoo become my<b>foo</b> or should it be ignored? If you want to only match whole words, then you'll need something like:

div.innerHTML = div.textContent.replace(/(\b|\s)(foo)(\b|\s)/g,'$1<b>$2<\/b>$3');

This is one of those cases where you can make your life much easier by restricting the applicability of your solution (say to just the plain text content of an element), a general solution will be quite unwieldy.

like image 44
RobG Avatar answered Feb 01 '26 14:02

RobG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!