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, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
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 <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....
How to replace only some tags (specified in doNoSubstituteArray)?