Skip to content

Instantly share code, notes, and snippets.

@aniruddhanath
Created December 28, 2015 12:19
Show Gist options
  • Save aniruddhanath/d9e1ff98d61704f325a7 to your computer and use it in GitHub Desktop.
Save aniruddhanath/d9e1ff98d61704f325a7 to your computer and use it in GitHub Desktop.
JavaScript global match group and replace
var hash = { prop_a: "abc", prop_b: "def", prop_c: "ghi" };
function getMatches (string, regex) {
var match;
while (match = regex.exec(string)) {
var prop = match[1];
string = string.slice(0, match.index) + hash[prop] + string.slice(match.index + prop.length + 4);
}
output = string;
}
// Example :
var input = '{{prop_a}} calls {{prop_c}} as {{prop_b}}',
myRegEx = /{{([^{}]*)}}/,
output;
getMatches(input, myRegEx);
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment