Saturday, February 27, 2016

How to replace all occurences of a string using a variable in regex in #javascript

Problem
I want to replace all occurrences of words in a substitution dictionary

My small substitution dictionary is a javascript object like this {"utilize":"use"}

Solution

1. Loop through the substitution dictionary using jQuery.each
2. we have to use the javascript string function .replace with regex. 
3. You might typically hardcode the pattern like this .replace(/replaceThis/g, "withThis"). Instead we want to use the substitution value from the dictionary. In order to do this we need to use a RegEx object. Instead of /replaceThis/g we use new RegEx(patternVariable, "g")

Example code
var targetText = $("#targetText")

    $.each(wordSubsfunction(key, value){

        targetText targetText .replace(new RegExp(key, "g"), value)
    })



References
1. http://stackoverflow.com/a/494046/1538717 

No comments:

Post a Comment

There was an error in this gadget