查找和替换HTML字符串。忽略网址

时间:2016-02-12 23:34:44

标签: jquery dom replace

我编写了一个基本脚本来搜索DOM中的字符串并替换。但在目前的状态下,它也会影响链接的URL。

例如替换"示例"用"我的例子"会破坏以下例子;

<a href="http://my example.com/my example">My Example</a>

我怎么能阻止这种情况发生,所以结果实际上会像这样回来?

<a href="http://example.com/example">My Example</a>

有没有办法自动计算CAP,还是需要单独的搜索字符串?

这是我的代码;

$(document).ready(function(){

    $("body").children().each(function() {           

        $(this).html($(this).html().replace(/example/g,"my example"));

    })

});

从灌注的角度来看,有大约80个单词要查找/替换,是否有更好的方法来处理这个问题?当然,每种语言都没有单独的页面。

1 个答案:

答案 0 :(得分:3)

如果使用.text()而不是.html(),则不会更改href。

$(document).ready(function(){
    $("body").children().each(function() {           
        $(this).text($(this).text().replace(/example/g,"my example"));
    });
});

更新:我应该补充一点,这可能会导致当前写入的意外副作用。我建议将.replace操作限制为原子元素,如下所示:

$(document).ready(function() {
    replaceText($("body"));

    function replaceText(object) {
        var children = object.children();
        if (children.length > 0) {
            children.each(function() {
                replaceText($(this));
            });
        } else {
            object.text(object.text().replace(/example/g, "my example"));
        };
    };
});

更新:这是一种适用于自由浮动文本节点的替代方法。

$(document).ready(function() {
    replaceText($("body"));

    function replaceText(object) {

        //first we handle text nodes inside the element itself
        handleTextNodes(object); 

        //then we iterate down into the child elements 
        var children = object.children();
        children.each(function() {
            replaceText($(this));
        });
    };

    function handleTextNodes(object) {
        object.contents().filter(function() {
            return this.nodeType == 3;
        }).each(function() {
            textNodeReplace(this);
        });
    };

    function textNodeReplace(node) {
        var text = node.nodeValue;
        node.nodeValue = text.replace(/example/g, "my example");
    };
});