Maurice Kroon
Maurice Kroon

Reputation: 959

Replace sentences with Regex in JS

I've got the following 'dictionary':

var dictionary = {
    "Log in again": "Just do it again",
    "Test phrase": "Lorem ipsum",
    "word": "other word"
}

Once the html page is loaded, I want these to load as well.

Here's the full source: http://jsfiddle.net/GMJ7y/

Right now I'm struggling: Sometimes it's a word, sometimes it's a full sentence. Right now I can only make it work with words.

Anybody know how I can do the sentences?

Upvotes: 0

Views: 791

Answers (1)

Rob W
Rob W

Reputation: 348972

The following solution has the desired result, and it's also more efficient. I have only included the relevant code, see the linked fiddle for the implementation.

var generatedReplace = [];         // Create list
for(var key in dictionary) {       // Loop through the dictionary
    var word = key.replace(/([[^$.|?*+(){}])/g, '\\$1');
    generatedReplace.push(word);   // Adds RegExp-string to the list
}
generatedReplace = "\\b(?:" + generatedReplace.join("|") + ")\\b"; //Finish RegExp
generatedReplace = new RegExp(generatedReplace, "g");          // Create RegExp

// Implementation:
$("body *").replaceText(generatedReplace, get_definition );

Fiddle: http://jsfiddle.net/GMJ7y/13/

Upvotes: 4

Related Questions