2

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!

Osman
  • 303
  • 1
  • 3
  • 14

2 Answers2

7

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.

jconder
  • 686
  • 4
  • 9
1

Regex helps in your concern of replacement.

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

console.log(str);
Duc Filan
  • 6,769
  • 3
  • 21
  • 26