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

时间:2011-12-07 10:14:59

标签: javascript search dictionary

我正在尝试执行字典查找某些内容和我的方法到目前为止我只能查找单个单词,因为我正在使用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);
}

以上示例不起作用。但是我字典中的一些东西会是这样的。我该如何解决这个问题,如果可能的话,也可以避免这种情况?谢谢!

1 个答案:

答案 0 :(得分:3)

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

演示: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];
});