我试图用正则表达式替换HTML内容.
从
<A HREF="ZZZ">test test ZZZ<SPAN>ZZZ test test</SPAN></A>
Run Code Online (Sandbox Code Playgroud)
至
<A HREF="ZZZ">test test AAA<SPAN>AAA test test</SPAN></A>
Run Code Online (Sandbox Code Playgroud)
请注意,只有HTML标记之外的单词才会从ZZZ替换为AAA.
任何的想法?非常感谢提前.
您可以遍历所有节点,替换文本节点中的文本(.nodeType == 3):
就像是:
element.find('*:contains(ZZZ)').contents().each(function () {
if (this.nodeType === 3)
this.nodeValue = this.nodeValue.replace(/ZZZ/g,'AAA')
})
Run Code Online (Sandbox Code Playgroud)
或者没有jQuery:
function replaceText(element, from, to) {
for (var child = element.firstChild; child !== null; child = child.nextSibling) {
if (child.nodeType === 3)
this.nodeValue = this.nodeValue.replace(from,to)
else if (child.nodeType === 1)
replaceText(child, from, to);
}
}
replaceText(element, /ZZZ/g, 'AAA');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1879 次 |
| 最近记录: |