Skip to content

Instantly share code, notes, and snippets.

@lstebner
Created August 30, 2012 19:34
Show Gist options
  • Save lstebner/3538727 to your computer and use it in GitHub Desktop.
Save lstebner/3538727 to your computer and use it in GitHub Desktop.
Underscore mixin for making multiple string replacements in one call
//this replace method can take multiple finds and one or multiple replacements at a time
//if find is an array, replace will be called on every find
//if replace is an array, the indexes must match with find to do replacements.
//if replace is a string, it will be used for all replace calls if find is an array
//if find and replace are both strings, this will simply mimmick a normal str.replace(find, replace) call
//the result of all replacements will be returned at the end
_.mixin({
replace: function(str, find, replace){
//if str is null, just give up now
if (str === null){
return str;
}
//explicity cast to string otherwise .replace() does not exist
str = str.toString();
//if find is an array we are going to be replacing a series of things
if (_.isArray(find)){
//go through each thing to find
_.each(find, function(v, k){
var replace_with = '';
//if replacements is an array use the 'replace' at the same index as the current 'find'
if (_.isArray(replace)){
replace_with = replace[k];
}
//otherwise just replace with the string sent
else{
replace_with = replace;
}
//do the replacement
str = str.replace(new RegExp(v, 'g'), replace_with);
});
}
//nothing fancy, do a normal replacement
else{
str = str.replace(new RegExp(v, 'g'), replace);
}
//return the string with replacements applied
return str;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment