0

Lets say I had some HTML code, such as:

"Hello, my <strong>name</strong> is Nanoo."

How could I replace the <strong> tag with a string?

For example:

"Hello, my **name** is Nanoo."

(Replaces the <strong> tag with **)

I could probably use the replace() function, however I want to do this efficiently.
Thanks for any help.

Nanoo
  • 836
  • 8
  • 16

2 Answers2

0

Use a regular expression. ((.+?) is used to capture the contents of the strong tag, so we can use $1 in the replacement to substitute the captured group.)

However, don't use regexps to really parse HTML.

>>> s = "Hello, my <strong>name</strong> is Nanoo.";
>>> s.replace(/<strong>(.+?)<\/strong>/g, '**$1**');
"Hello, my **name** is Nanoo."
AKX
  • 152,115
  • 15
  • 115
  • 172
0

Use parentNode.replaceChild(newChild, oldChild);.

// on DOMContentLoaded 
document.querySelectorAll('strong').forEach(function(ele) { // for each strong tag
    var newTag = document.createTextNode('**' + ele.textContent + '**');
    ele.parentNode.replaceChild(newTag, ele);
})
<p>Hello, my <strong>name</strong> is Nanoo.</p>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61