find multiple key words within a dictionary Javascript

冷暖自知 提交于 2019-12-19 11:35:49

问题


I am trying to perform a dictionary look up on some content and my approach so far I can only look up single words because I am using the split(' ') method splitting on just the space. I just ran into a sorta blockage and was wondering if guys you had any solid input. like what if I have keys in my dictionary that are of two words. Like below

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"} 

this is the code I got so far and it works for single words obviously but not muliplte key words. getElementsByClassName is a function to return an array of all classes found.

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);
}

The above example wouldn't work. However Some of the things in my dictionary are gonna be like this. How should I go about this and maybe avoid case as well if at all possible? Thanks!


回答1:


Construct a RegEx, consisting of all keys of the dictionary (to prevent a replacement from being replaced again). Then, use String.replace(pattern, replace_function) as shown below.

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


来源:https://stackoverflow.com/questions/8413651/find-multiple-key-words-within-a-dictionary-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!