简体   繁体   中英

How to replace text containing string with a HTML tag?

I am trying to work out how to replace any instance of text on page matching a certain phrase with a HTML tag - the contents should remain the same.

bold("Hello")

The code above should be replaced with:

<b>Hello</b>

Here is the code that I am currently using:

node.data = node.data.replace('bold("','<b>');
node.data = node.data.replace('")','</b>');

The problem with this is that rather than creating a <b> tag, it converts the < and > into their HTML entities - &lt; &gt; .

Also, it seems unpractical to replace all instances of ") with </b> .

What would be the best way to achieve this.

I would appreciate any help with this, thank you!

I assume you don't literally mean all text on a page, but rather all text inside of a given element. DucFilans is right on the money with regex, I'll slightly modify his answer to provide a complete working solution:

 var parserRules = [ { pattern: /bold\\("(.*?)"\\)/g, replacement: '<b>$1</b>' }, { pattern: /italics\\("(.*?)"\\)/g, replacement: '<i>$1</i>' } ]; document.querySelectorAll('.parse').forEach(function(tag) { var inner = tag.innerHTML; parserRules.forEach(function(rule) { inner = inner.replace(rule.pattern, rule.replacement) }); tag.innerHTML = inner; }); 
 <div class='parse'> <div>bold("Hello") world <p> Rose italics("pink") slow bold("!") </p> </div> <div>bold("astiago") cheeeeeeese!</div> </div> 

You can define the regex patterns and replacement rules in the parserRules array, and then any element marked with the 'parse' class will be parsed. One warning is that this will replace all of the subelements, so if you are relying on listeners attached to subelements or something similar you'll need to take care of that as well.

Regex helps in your concern of replacement.

 var str = 'bold("Hello")'; var regex = /bold\\("(.*?)"\\)/; str = str.replace(regex, "<b>$1</b>"); console.log(str); 

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