在JavaScript中,如何在不影响标记的情况下替换HTML页面中的文本?

Phi*_*hil 5 javascript regex dom

我正在试图弄清楚如何用Javascript替换.我正在查看页面的整个主体,并希望替换HTML标记中的关键字匹配.

这是一个例子:

<body>
  <span id="keyword">blah</span>
  <div>
    blah blah keyword blah<br />
    whatever keyword whatever
  </div>
</body>

<script type="text/javascript">
var replace_terms = {
  'keyword':{'url':'http://en.wikipedia.org/','target':'_blank'}
}

jQuery.each(replace_terms, function(i, val) {
  var re = new RegExp(i, "gi");
  $('body').html(
    $('body').html().replace(re, '<a href="'+ val['url'] +'" target="'+val['target']+'">' + i + '</a>')
  );
});

</script>
Run Code Online (Sandbox Code Playgroud)

我想要替换不在HTML标记内的"关键字"的所有实例(在<和之间>).

我想我还需要忽略"关键字"是否在a scriptstyle元素中.

bob*_*nce 13

不要使用正则表达式来解析HTML.[X] [HT] ML不是常规语言,无法使用正则表达式进行可靠处理.您的浏览器内置了一个很好的HTML解析器; 让这需要解决标签所在的问题.

另外,你真的不想html()/innerHTML在身体上工作.这将序列化并重新解析整个页面,这将很慢并且将丢失任何无法在HTML中序列化的信息,例如事件处理程序,表单值和其他JavaScript引用.

这是一个使用DOM的方法,似乎对我有用:

function replaceInElement(element, find, replace) {
    // iterate over child nodes in reverse, as replacement may increase
    // length of child node list.
    for (var i= element.childNodes.length; i-->0;) {
        var child= element.childNodes[i];
        if (child.nodeType==1) { // ELEMENT_NODE
            var tag= child.nodeName.toLowerCase();
            if (tag!='style' && tag!='script') // special case, don't touch CDATA elements
                replaceInElement(child, find, replace);
        } else if (child.nodeType==3) { // TEXT_NODE
            replaceInText(child, find, replace);
        }
    }
}
function replaceInText(text, find, replace) {
    var match;
    var matches= [];
    while (match= find.exec(text.data))
        matches.push(match);
    for (var i= matches.length; i-->0;) {
        match= matches[i];
        text.splitText(match.index);
        text.nextSibling.splitText(match[0].length);
        text.parentNode.replaceChild(replace(match), text.nextSibling);
    }
}

// keywords to match. This *must* be a 'g'lobal regexp or it'll fail bad
var find= /\b(keyword|whatever)\b/gi;

// replace matched strings with wiki links
replaceInElement(document.body, find, function(match) {
    var link= document.createElement('a');
    link.href= 'http://en.wikipedia.org/wiki/'+match[0];
    link.appendChild(document.createTextNode(match[0]));
    return link;
});
Run Code Online (Sandbox Code Playgroud)

  • 我不能因此而声称,它是C语言中反向迭代的习惯用语!:-) (2认同)