简体   繁体   中英

How to search a particular text within an HTML Text and highlight the search string with a color

We have requirement to search through a HTML text and highlight the text with a particular color.

Ex: The html string is

<p class="Pa0" style="margin: 0in 0in 0pt;"><span class="A1"><span style="font-size: 10pt;">Giving this flyer to your class customers</span></span></p>

In the above text I am searching for the word "Class". It should highlight the text class within the text "Giving this flyer to your class customers" But whereas it is trying to highlight the css element "class" and as a result the original html text is corrupted and not displayed properly.

Can anyone help me in resolving this issue on how to search a content within an HTML text and highlight the search without changing the original HTML.

It is possible with javascript:

var str = document.getElementByClassName("Pa0")[0].children[0].children[0];
str.innerHTML = str.innerHTML.replace(' class ', ' <span style="color:red">class</span> ')
(class)(?=(?:[^><]*<[^<>]*>)*[^><]*$)

Try this.Replace by <span style='color: red;'>$1<span> .See demo.

http://regex101.com/r/bB8jY7/3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM