Search and highlight in html with multiple keywords as a single string

Posted by Qiusheng on Stack Overflow See other posts from Stack Overflow or by Qiusheng
Published on 2014-05-29T21:18:28Z Indexed on 2014/05/29 21:26 UTC
Read the original article Hit count: 148

Filed under:
|
|
|
|

In JavaScript, by given a html string with tags like: This string has different fonts.

<b>This</b>
<i>string</i>
<span style="background-color: rgb(212, 239, 181);">has</span>
<b>different</b>
<i>fonts</i>.

When user searches for a search term with multiple words like "different fonts".

How can I add highlighting to make the html string look like:

<b>This</b>
<i>string</i>
<span style="background-color: rgb(212, 239, 181);">has</span>
<span class="highlight">
    <b>different</b>
    <i>fonts</i>
</span>.

Please note that the search term is treated as a single string as if the words are in a quote, so I cannot search and highlight each word individually.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery