Issue
This Content is from Stack Overflow. Question asked by xaaaaaaaaaaaa
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 #idname
it’s a textarea
here the start code
var doNoSubstituteArray = ['br','div'];
let htmlString = $('#idname').val();
let htmlDoc = (new DOMParser()).parseFromString(htmlString, "text/html");
let tags = htmlDoc.getElementsByTagName('*');
But then?
How to replace only some tags (specified in doNoSubstituteArray
)?
Solution
There is a problem with your solution code–it will only escape the first occurrence of each special character. For example:
escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual: Kip's <b>evil</b> "test" code's here
Expected: Kip's <b>evil</b> "test" code's here
Here is code that works properly:
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Update
The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks jbo5112).
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
This Question was asked in StackOverflow by Bart van Heukelom and Answered by Kip It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.