使用regex解释不同类型的变量,并使用jquery进行查找和替换

Use regex to interpret different type of variable and do a find and replace with jquery

本文关键字:jquery 查找 替换 解释 regex 同类型 变量 使用      更新时间:2023-09-26

好吧,我很难理解rejex和它是如何工作的,我试着为一个网站做一个基本的词典/词汇表,我已经在上面花了太多时间了。

这是我的代码:

// MY MULTIPLE ARRAY
var myDictionnary = new Object();
myDictionnary.myDefinition = new Array();
myDictionnary.myDefinition.push({'term':"*1", 'definition':"My description here"});
myDictionnary.myDefinition.push({'term':"word", 'definition':"My description here"});
myDictionnary.myDefinition.push({'term':"my dog doesn't move", 'definition':"My description here"});
// MY FUNCTION
$.each(myDictionnary.myDefinition, function(){
    var myContent = $('#content_right').html();
    var myTerm = this.term;
    var myRegTerm = new RegExp(myTerm,'g');
    $('#content_right').html(myContent.replace(myRegTerm,'<span class="tooltip" title="'+this.definition+'"> *'+this.term+'</span>'));
});

我创建了我的数组,对于每个结果,我在我的div#content_right中搜索相同的内容,并将其替换为带有标题和工具提示的span。我把我的正则表达式为空,以避免与我之前尝试过的内容混淆。

在我的数组'term'中,你可以看到我将研究什么样的文本。它适用于搜索普通文本,如"word"。

但是对于像'asterix'这样的正则表达式,当我找到一种方法来传递它时,他将它添加到文本中,我尝试了许多方法来解释我的'asterix'像一个正常的字符,但它不起作用。

这就是我想要的:从字面上解释变量,无论我的var 'myTerm'中的文本是什么。这可能吗?如果不是,我应该用什么样的解决方案。

提前感谢,附言:对不起,我的英语很差…法国(im)亚历克斯

*是Regex中的一个特殊字符,表示"前一个字符的0或更多"。因为它是第一个字符,所以它是无效的,你会得到一个错误。

考虑从PHPJS实现preg_quote来转义这些特殊字符,并使它们在正则表达式中有效使用。


然而,你这样做的方式是非常糟糕的。不仅因为你多次使用innerHTML,还因为如果你遇到这样的情况怎么办?

Blah blah blah <img src="blah/word/blah.png" />

您的输出结果将是:

Blah blah blah <img src="blah/<span class="tooltip" title="My description here"> *word</span>/blah.png" />

唯一真正的方法是专门扫描文本节点,然后在文本节点上使用.splitText()来提取单词匹配,然后将其放入自己的<span>标记中。


下面是上述解释的一个示例实现:

function definitions(rootnode) {
    if( !rootnode) rootnode = document.body;
    var dictionary = [
        {"term":"*1", "definition":"My description here"},
        {"term":"word", "definition":"My description here"},
        {"term":"my dog doesn't move", "definition":"My description here"}
    ], dl = dictionary.length, recurse = function(node) {
        var c = node.childNodes, cl = c.length, i, j, s, io;
        for( i=0; i<cl; i++) {
            if( c[i].nodeType == 1) { // ELEMENT NODE
                if( c[i].className.match(/'btooltip'b/)) continue;
                // ^ Exclude elements that are already tooltips
                recurse(c[i]);
                continue;
            }
            if( c[i].nodeType == 3) { // TEXT NODE
                for( j=0; j<dl; j++) {
                    if( (io = c[i].nodeValue.indexOf(dictionary[j].term)) > -1) {
                        c[i].splitText(io+dictionary[j].term.length);
                        c[i].splitText(io);
                        cl += 2; // we created two new nodes
                        i++; // go to next sibling, the matched word
                        s = document.createElement('span');
                        s.className = "tooltip";
                        s.title = dictionary[j].definition;
                        node.insertBefore(s,c[i]);
                        i++;
                        s.appendChild(c[i]); // place the text node inside the span
                        // Note that now when i++ it will point to the tail,
                        // so multiple matches in the same node are possible.
                    }
                }
            }
        }
    };
    recurse(rootnode);
}

现在您可以调用definitions()来替换文档中的所有匹配项,或者调用definitions(document.getElementById("myelement"))来仅替换特定容器中的匹配项。

通过添加另一个变量,它将解决这个问题:

            for( j=0; j<dl; j++) {
                  debutI =i;
                  if((io =c[i].nodeValue.indexOf(dictionary[j].term)) != -1) {
                        c[i].splitText(io+dictionary[j].term.length);
                        c[i].splitText(io);
                        cl += 2; // we created two new nodes
                        i++; // go to next sibling, the matched word
                        s = document.createElement('span');
                        s.className = "tooltip";
                        s.title = dictionary[j].definition;
                        node.insertBefore(s,c[i]);
                        i++;
                        s.appendChild(c[i]); // place the text node inside the span
                        // Note that now when i++ it will point to the tail,
                        // so multiple matches in the same node are possible.
                    }
                    i = debutI;
                }

Comme。> _ >