在Javascript字典中查找多个关键词

2023-12-04

我正在尝试对某些内容执行字典查找,到目前为止我的方法只能查找单个单词,因为我使用 split(' ') 方法仅在空格上进行分割。我刚刚遇到了一些障碍,想知道你们是否有任何可靠的意见。就像如果我的字典中有两个单词的键怎么办?像下面这样

var  dictionary = { "Darth Vader" : "Bad Ass Father", "Luke": "Son of the Bad Ass",
"Skywalker" : "Last name of some Jedi Knights", "Luke SkyWalker" : "Son of the Bad Ass"} 

这是我到目前为止得到的代码,它显然适用于单个单词,但不适用于多个关键字。 getElementsByClassName 是一个返回找到的所有类的数组的函数。

var body = '<div class="activity-inner"> This is a test glossary body paragraph to test glossary highlight of the Star Wars vocabulary. like Luke Skywalker and Darth Vader, Luke and Skywalker. </div> <div class="activity-inner">Hello glossary again here Luke Skywalker Darth Vader</div>';
document.write( body);
var matches = getElementsByClassName("activity-inner");
for (int i = 0; i < matches.length; i++;) {
var content = matches[i].innerHTML;
document.write(content);
var  words = content.split(' ');



for (var j = 0; j < words.length; j++) {
var temp = words[j].replace(/[^\w\s]|_/g, "")
     .replace(/\s+/g, " ").toLowerCase();
 if (temp in dictionary) {
words[j] = "<span class='highlight' style='color:green;'>"+words[j]+"</span>";
}
document.write(words[j] +"<br />");



}
body = words.join(' ');
document.write( "<br /> <br />" + body);
}

上面的例子是行不通的。然而我的字典里有些东西会是这样的。我应该如何解决这个问题,如果可能的话,也可以避免这种情况?谢谢!


构造一个正则表达式,由字典的所有键组成(以防止替换被再次替换)。然后,使用String.replace(pattern, replace_function)如下所示。

Demo: http://jsfiddle.net/Z7DqF/

// Example
var dictionary = { "Darth Vader" : "Bad Ass Father", "Luke": "Son of the Bad Ass",
"Skywalker" : "Last name of some Jedi Knights", "Luke SkyWalker" : "Son of the Bad Ass"}
    content = "....";

var pattern = [],
    key;
for (key in dictionary) {
    // Sanitize the key, and push it in the list
    pattern.push(key.replace(/([[^$.|?*+(){}])/g, '\\$1'));
}
pattern = "(?:" + pattern.join(")|(?:") + ")"; //Create pattern
pattern = new RegExp(pattern, "g");

// Walk through the string, and replace every occurrence of the matched tokens
content = content.replace(pattern, function(full_match){
    return dictionary[full_match];
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Javascript字典中查找多个关键词 的相关文章

随机推荐