Skip to content

Instantly share code, notes, and snippets.

@nebiros
Created March 15, 2012 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebiros/2044642 to your computer and use it in GitHub Desktop.
Save nebiros/2044642 to your computer and use it in GitHub Desktop.
javascript multi-replace
var str = "/activity_sets/:activity_set_id/activity_set_annotations/:id/edit John Smith"
, repl = {
"11": ":activity_set_id",
"1": ":id",
"$2, $1": new RegExp("(John)\\s(Smith)", "gi")
};
function multi_replace(str, repl) {
if (!str) return str;
if (typeof repl != "object") return str;
for (r in repl) {
var pattern = repl[r];
if (Object.prototype.toString.call(pattern) != "[object RegExp]") pattern = new RegExp(pattern);
str = str.replace(pattern, r);
}
return str;
}
var s = multi_replace(str, repl);
console.log(s); // /activity_sets/11/activity_set_annotations/1/edit Smith, John
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment