简体   繁体   English

纯Javascript-查找/替换DOM中的单词列表

[英]Pure Javascript - Find/Replace a list of words in DOM

I have a list of words and I want to replace them in DOM. 我有一个单词列表,我想在DOM中替换它们。

The replace is working but it has an issue. 替换有效,但是有问题。 Before and after the replaced text, it puts an undesired slash bar (ie reduced to a brigade > reduced/ OTHER WORD 1 /a brigade) 在替换的文本前后,它放置了一个不希望的斜杠(即减少为一个旅>减少/ OTHER WORD 1 /一个旅)

Also, I need to wrap the replaced word with an html tag, like . 另外,我需要用html标签包装替换的单词,例如。 (ie reduced to a brigade > reduced OTHER WORD 1 a brigade) (即简化为一个旅>将OTHER WORD 1简化为一个旅)

You can see the code here: https://jsfiddle.net/realgrillo/9uL6ofge/ 您可以在此处查看代码: https : //jsfiddle.net/realgrillo/9uL6ofge/

var elements = document.getElementsByTagName('*');

var words = [

    [/(^|\s)([Tt]o)(\s|$)/ig, 'OTHER WORD 1'],
    [/(^|\s)([Aa]nd)(\s|$)/ig, 'OTHER WORD 2']

];

for (var i = 0; i < elements.length; i++) {
    var element = elements[i];

    for (var j = 0; j < element.childNodes.length; j++) {

        var node = element.childNodes[j];

        if (node.nodeType === 3) {

            var text = node.data;

            for (var k = 0; k < words.length; k++)
            {
                var from = new RegExp(words[k][0]);
                var to = new RegExp('$1' + words[k][1] + '$3');
                var replacedText = text.replace(from, to);

                //console.log("from: " + from);
                //console.log("to: " + to);
                //console.log("toDo: " + toDo);

                if (replacedText !== text)
                {
                    element.innerHTML = element.textContent.replace(from, to);
                    console.log("text: " + text);
                    console.log("replacedText: " + replacedText);
                }
            }

            /*
            //
            //!!!!THIS CODE FOR 1 WORD WORKS!!!! I need to do this for the list of words.
            //
            var replacedText = text.replace(/(^|\s)([Tt]o)(\s|$)/ig, '$1OTHER WORD$3');

            if (replacedText !== text) {

                element.innerHTML = element.textContent.replace(/(^|\s)([Tt]o)(\s|$)/ig, '$1<b class=modified>OTHER WORD</b>$3');
            }
            */
        }
    }
}

Masters of JS, can you help me? JS大师,您能帮我吗? Pure javascript, not jQuery please. 纯JavaScript,而不是jQuery。

Thanks. 谢谢。

I can give you some much more simple function to use. 我可以给您一些更简单的功能。 First define a function for replacing words like this: 首先定义一个函数来替换这样的单词:

String.prototype.replaceAll = function (search, replacement) {
            try {
                var target = this;
                return target.split(search).join(replacement);
            } catch (e) {
                return "";
            }
        };

That's why the pure javascript replace function only replace one time in a whole case. 这就是纯JavaScript replace功能在整个情况下只能替换一次的原因。 After that you can use it in your code like here: 之后,您可以像下面这样在代码中使用它:

var replacedText = text.replaceAll(/(^|\s)([Tt]o)(\s|$)/ig, '$1OTHER WORD$3');

You don't need to parse words[k][0] into a RegExp as it is already one, even though it won't break because the constructor will handle a RegExp well. 您无需将words[k][0]解析为一个RegExp ,尽管它不会中断,因为构造函数可以很好地处理RegExp ,所以它不会中断。

Also for the words[k][1] , you don't need to parse it into a RegExp either because the second parameter of String.prototype.replace is expected to be a plain string. 同样对于words[k][1] ,您也不需要将其解析为RegExp ,因为String.prototype.replace的第二个参数应该是纯字符串。 The slashes are there because you cast your RegExp to a string (and will end up output). 因为您将RegExp转换为字符串(并将最终输出),所以存在斜线。

So this is a change that will fix it: 因此,此更改将解决此问题:

var to = '$1' + words[k][1] + '$3';

And this is optional but probably a good practice: 这是可选的,但可能是一个好习惯:

var from = words[k][0];

For getting an html tag, you can either change it directly in each words[k][1] or in the to var declaration, depending on what you want. 要获取html标记,您可以根据需要直接在每个words[k][1]to var声明中对其进行to


Extra: 额外:

In the for loop, the code assumes that there are always at least three groups (because of the '$3' reference), an alternative could be to delegate this replacement directly in words[k][1] , but it is up to you to decide. 在for循环中,代码假定始终至少存在三个组(由于使用了'$3'引用),一种替代方法是直接用words[k][1]委派此替换,但这取决于您决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM