Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中,如何在不影响标记的情况下替换HTML页面中的文本?_Javascript_Regex_Dom - Fatal编程技术网

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

在JavaScript中,如何在不影响标记的情况下替换HTML页面中的文本?,javascript,regex,dom,Javascript,Regex,Dom,我正试图找出如何用Javascript进行替换。我正在查看页面的整个主体,希望替换不在HTML标记中的关键字匹配项 以下是一个例子: <body> <span id="keyword">blah</span> <div> blah blah keyword blah<br /> whatever keyword whatever </div> </body> <script t

我正试图找出如何用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>

废话
废话废话关键字废话
随便什么关键字随便什么 变量替换项={ '关键字':{'url':'http://en.wikipedia.org/“,”目标“:”空白“} } jQuery.each(替换_术语、函数(i、val){ var re=新的RegExp(i,“gi”); $('body').html( $('body').html().replace(re')) ); });
我希望替换HTML标记之外的所有“关键字”实例(介于
之间)


我想如果“关键字”在
脚本
样式
元素中,我也需要忽略。

不要使用正则表达式解析HTML。[十] [HT]ML不是一种常规语言,无法使用正则表达式可靠地进行处理。你的浏览器内置了一个很好的HTML解析器;让我们来看看标签在哪里

另外,您也不想在body上处理
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;
});

根据定义,整个页面不是在HTML标记中吗?是的。我在示例中使用的HTML没有通过。我的基本意思是我不想替换标记的任何属性。我想他指的是括号内的属性(如属性名称/值)。标记中的属性介于<和>。介于和之间将位于元素中:)
i-->0
聪明。我以前从未见过这种情况。我不能说这是一种功劳,这是类C语言中反向迭代的习惯用法!:-)我通常只使用
I--
,如:
for(var I=100;I--;)
是的,这也适用于下限0。显式
>0
也是一种防御措施,用于
i
可能以负数开始的情况(这将无休止地循环)。我喜欢
i-->0
的一点是,我第一次读它时→0,或“我接近零。”