javascript - Javascript - 使用jQuery替换字母

119 4


javascript: $("body").text($("body").text().replace("r","w"));



Hello ,my name is Jonathan Grasswell ,and i would like to propose a new idea for a tractor .

替换成:

Hewwo ,my nyame is Jonnyathyan Gwyassweww ,aynd i wouwd wike to pwopose a nyew ideya fow ay twactow .

时间: 原作者:

133 5



const body = document.body; // Or whatever more specific element you desire


const repl = { // Your replacements:


"l" :"w",


"L" :"W",


"r" :"w",


"R" :"W",


"." :". :)" // Remember, escape RegExp special characters to treat them as literals


};



const treeWalker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);



while (treeWalker.nextNode()) {


 const Node = treeWalker.currentNode; // PS: Node.nodeType is always 3 


 Object.keys(repl).forEach(key => {


 Node.nodeValue = Node.nodeValue.replace(new RegExp(key,"g"), repl[key]);


 });


}
.hello, .ll {color: BURLYWOOD;} /*"l"s of"class" and"hello" will stay intact */

<h1 class="hello">Hello,</h1>


<p>


 my name is <b class="ll">Long Island</b>, 


 and I would like to propose a new idea. For a clock. LOL


</p>

原作者:
146 4

方法text()只返回正文的文本内容。

使用这个函数,通过按F12在页面下运行这个函数,"Jonathan "使用"ABCDEFGHIJKLMN"替换。


function replaceTextOfElement(element) {


 $(element).contents()


 .filter((_, child) => child.tagName !== 'SCRIPT' && child.tagName !== 'STYLE' && child.tagName !== 'IFRAME')


 .each((_, child) => {


 if(child.nodeType === Node.TEXT_NODE) {


 child.data = child.data.replace('Jonathan', 'ABCDEFGHIJKLMN');


 } else {


 replaceTextOfElement(child);


 }


 });


}


replaceTextOfElement($('body'));



原作者:
...