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