Javascript replace all occurrences of a string only once

When building a Javascript endless scroll, I wanted to use variable place holders in a template which I could then replace with the data returned from an ajax request.


I initially did this by looping through my data object and using a greedy regular expression to replace each occurrence of a place holder with the returned data.

This leads to a problem if the data contains a string which is also used as a place holder.

var reps = {
   UN: "Ali",
   LC: "Turkey",
   AG: "29",
   ...
};

return str.replace(/\[(\w+)\]/g, function(s, key) {
    return reps[key] || s;
});

I found quite an elegant solution to this on stackoverflow which utilises Javascript’s string.replace(regex, funtion()) function. The mapping function is passed each of the matched groups as a parameter. My function then looks up the matched placeholder in the data array and returns the data if found, otherwise leaves the placeholder untouched.

I have then modified the code to allow me to use place holders with curly braces like so:

{some_variable_name}

function cloneIdea(data){
       var clone = jQuery('.idea_clone').html();

       // Replace all occurrances of {SOME_KEY} with the key value from reps (our returned data)
       // %7b = { and %7D = } because for some reason, the image src is returned from .html() as url encoded
       clone = clone.replace(/(\{|%7B)(\w+)(\}|%7D)/g, function(orig,p2,key) {
              // This function is called with the parameters matches from the regex,
              // Only return the value from data if it's defined. If not, don't replace.
              return (typeof(data[key]) != 'undefined')?data[key]:orig;
       });

       return clone;
}


Note that the function is passed parameters of the matched groups (round brackets) in the regular expression in the order they occur. I experimented a bit with this functionality, and am still as little confused as to why it works the way it does since the MDN docs seem to suggest that you use parameters named p1, p2, pn… to get the matches.

The expression itself works as follows:

  • (\{|%7B) The round brackets create a group so that you can use the | as an OR. The \ escapes the { as it is a special character. %7B is the percent encoded character for {
  • (\w+) Creates another group, \w is the special character class for a ‘word‘ character, the + indicates that there should be 1 or more of those characters.
  • (\}|%7D) This is the same as the first half but for matching the } character instead
  • The g at the end indicates that the regular expression should do a global match, i.e. not stop at the first instance.

I quite like this Regular Expression Cheat sheet.

Leave a Reply

Your email address will not be published. Required fields are marked *