Check If Document Contains Any String From Array And Replace It
Trying to check the document for any string in a given array and replace it with something matched string. I tried just looping through the array and replacing
Solution 1:
This is what I would do
function escapeRegExp(str) {
return str.replace(/[-[\/{}*+?.\\\]^$]/g, "\\$&");
}
var code = document.body.innerHTML;
array.forEach(function(v) {
code = code.replace(new RegExp(escapeRegExp(v)), "g"), "<em>"+v+"</em>")
}
document.body.innerHTML = code;
I am avoiding multiple assignments to innerHTML to avoid unnecessary reflows (performance)
Post a Comment for "Check If Document Contains Any String From Array And Replace It"