Created
March 15, 2012 14:58
-
-
Save nebiros/2044642 to your computer and use it in GitHub Desktop.
javascript multi-replace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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