find multiple key words within a dictionary Javascript

后端 未结 1 689
再見小時候
再見小時候 2021-01-16 15:01

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

相关标签:
1条回答
  • 2021-01-16 15:30

    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];
    });
    
    0 讨论(0)
提交回复
热议问题