Wrap words in tags, keep markup

Posted by spacevillain on Stack Overflow See other posts from Stack Overflow or by spacevillain
Published on 2012-06-03T16:31:31Z Indexed on 2012/06/03 16:40 UTC
Read the original article Hit count: 251

Filed under:
|
|

For example I have a string with markup (from html node):

hello, this is dog

"h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og"

What is the most correct way to find some words in it (let's say "hello" and "dog"), wrap them in a span (make a highlight) and save all the markup?

Desired output is something like this (notice properly closed tags)

<span class="highlight">h<em>e<strong>llo</strong></em></span><strong>,</strong> <em><strong>thi</strong>s<em> i</em><strong>s <span class="highlight"><strong>d</strong>og</span>

Looks the same as it should:

hello, this is dog

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html