在网页中查找"旧"的所有实例,并使用javascript bookmarklet将每个实例替换为"new"

14 javascript scripting greasemonkey replace bookmarklet

我想要做的是用JS书签或者greasemonkey脚本中的'new'替换网页中的所有'old'实例.我怎样才能做到这一点?我认为jQuery或其他框架是可以的,因为有些黑客将它们包含在bookmarklet和greasemonkey脚本中.

six*_*ear 26

一个防止破坏的功能.这意味着这不会触及任何标签或属性,只会触及文本.

function htmlreplace(a, b, element) {    
    if (!element) element = document.body;    
    var nodes = element.childNodes;
    for (var n=0; n<nodes.length; n++) {
        if (nodes[n].nodeType == Node.TEXT_NODE) {
            var r = new RegExp(a, 'gi');
            nodes[n].textContent = nodes[n].textContent.replace(r, b);
        } else {
            htmlreplace(a, b, nodes[n]);
        }
    }
}

htmlreplace('a', 'r');
Run Code Online (Sandbox Code Playgroud)

书签版本:

javascript:function htmlreplace(a,b,element){if(!element)element=document.body;var nodes=element.childNodes;for(var n=0;n<nodes.length;n++){if(nodes[n].nodeType==Node.TEXT_NODE){nodes[n].textContent=nodes[n].textContent.replace(new RegExp(a,'gi'),b);}else{htmlreplace(a,b,nodes[n]);}}}htmlreplace('old','new');
Run Code Online (Sandbox Code Playgroud)

  • 很抱歉重新访问这样一个旧帖子,但注意到你的正则表达式是在你的循环中构建的.为了提高效率,您真的应该在函数顶部创建一次regexp. (3认同)

Kan*_*ann -1

嘿,你可以尝试这个,问题是它会搜索整个身体,所以甚至属性等都会改变。

javascript:document.body.innerHTML=document.body.innerHTML.replace( /old/g, "new" );
Run Code Online (Sandbox Code Playgroud)