Reputation: 4908
I'm trying to replace all occurences of '$' (dollar sign) in a web page with another string.
The problem is that there may be some <script>
tags that may contain the '$' (jQuery code) that I don't want to change.
For example:
document.body.innerHTML = document.body.innerHTML.replace(/\$/g, 'xxx');
seems to work, but also replaces '$' from any <script>$('...')...</script>
parts.
Is this achievable?
Thank you in advance.
EDIT: I cannot modify the way the page is generated or change all other js parts - neither use some server-side logic. I can only add some custom js code
Upvotes: 1
Views: 969
Reputation: 526
function textNodes(main) {
var arr = [];
var loop = function(main) {
do {
if(main.hasChildNodes() && (["STYLE","SCRIPT"].indexOf(main.nodeName)==-1)){
loop(main.firstChild);
} else if(main.nodeType === 3) {
arr.push(main)
}
}
while (main = main.nextSibling);
}
loop(main);
return arr;
}
textNodes(document.body).forEach(function(a){a.textContent=a.textContent.replace(/\$/g,'€')});
Based on this DOM walking example
Upvotes: 0
Reputation: 318212
You can filter out the script tags
[].slice.call(document.body.children).forEach(function(element) {
if ( element.tagName.toLowerCase() != 'script' ) {
element.innerHTML = element.innerHTML.replace(/\$/g, 'xxx');
}
});
This is not recursive, which means it only works for script tags directly under the body tag, not script tags that are nested deeper
Upvotes: 1