简体   繁体   中英

Remove dollar sign from dom text - not from js code

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM