Created
December 28, 2015 12:19
-
-
Save aniruddhanath/d9e1ff98d61704f325a7 to your computer and use it in GitHub Desktop.
JavaScript global match group and replace
This file contains hidden or 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 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