正则表达式替换HTML内容

iwa*_*wan 2 javascript regex

我试图用正则表达式替换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.

任何的想法?非常感谢提前.

Suo*_*uor 7

您可以遍历所有节点,替换文本节点中的文本(.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)