Replacing only some tags in JavaScript / JQuery with HTML code

Viewed 40

There's a way to replace only some HTML tags with JQuery / JavaScript?

For all tags substitution can be used this function found over stackoverflow.com.

function escapeHtml(text) {
  return text
      .replace(/&/g, "&")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
}

But if I want replace only some HTML tags in a text (also nested) what have I do?

Regex for nested tags it's out of the game.

Something like a DOM parser could be this.

If #dt it's a textarea here the start code

var doNoSubstituteArray = ['br','div'];

function replaceTags(doNoSubstituteArray) {
  let htmlString = $('#dt').val();
  let htmlDoc = (new DOMParser()).parseFromString(htmlString, "text/html");
  let tags = htmlDoc.getElementsByTagName('*');
  [...]
}

But then?

Example of scenario using a demonstrative text (requested in comments)

Input in #dt from user:

<textarea id="dt">
Book traversal <a href="https://stackoverflow.com">links</a> other text for Demonstratives.
<div>Do you need to improve your <div>English <p>grammar</p></div>?</div>
Join thousands of learners from around the world who are improving....
</textarea>
<button type="button" onclick="replaceTags(doNoSubstituteArray);">Substitute</button>

Output:

Book traversal &lt;a href=&quot;https://stackoverflow.com&quot;&gt;links&lt;/a&gt; other text for Demonstratives.
<div>Do you need to improve your <div>English &lt;p&gt;grammar&lt;/p&gt;</div></div>
Join thousands of learners from around the world who are improving....

How to replace only some tags (specified in doNoSubstituteArray)?

0 Answers
Related