1

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

CdB
  • 4,738
  • 7
  • 46
  • 69
  • you can put script in footer or head tag as you are getting body's html – Umesh Sehta Nov 25 '14 at 10:48
  • Could you not specifically target the elements you require this replacement in? Or better yet, do the replacement on the server before the HTML is rendered. – Rory McCrossan Nov 25 '14 at 10:50
  • Hi @MohitArora, thanks for the comment. I cannot modify the way the page is generated, I can only put some extra custom javascript. – CdB Nov 25 '14 at 10:50
  • Like @RoryMcCrossan is saying, can't you add a class (eg. remove-dollar-sign) to the containers where you want to change the dollar sign? – Mivaweb Nov 25 '14 at 10:51
  • Do you have nested script tags below the body, as inside other elements and such strangeness, or just in the `body`? You could target `document.body.children` and filter out all script tags before replacing, but doing a string replace on all elements is generally a horrible idea. – adeneo Nov 25 '14 at 10:53
  • I'm not entirely sure, but if you change code in a script block that has already been executed it shouldn't make a difference; so, just make sure the replacement is done in the last block to run. – Ja͢ck Nov 25 '14 at 10:58

2 Answers2

1

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');
    }
});

FIDDLE

This is not recursive, which means it only works for script tags directly under the body tag, not script tags that are nested deeper

adeneo
  • 312,895
  • 29
  • 395
  • 388
0
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

Community
  • 1
  • 1
James Wakefield
  • 526
  • 3
  • 11