I just used a capturing group for the word inside the [~{ ... }~]
structure.
\[~\{ (\w+) \}~\]
The only difference is I matched (\w+)
instead of .*?
. I also removed the capture group ((...)
) that was around the whole expression, since it wasn't necessary.
Now it is a little difficult to access multiple capture groups in Javascript, but I used some example code from this answer (thanks Mathias Bynens):
function getMatches(string, regex) {
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match);
}
return matches;
}
var myString = $('body').html();
var myRegEx = /\[~\{ (\w+) \}~\]/g;
var matches = getMatches(myString, myRegEx);
console.log(matches[0]);
Output:
Array[2]
0: "[~{ header }~]" // The whole match
1: "header" // The captured group
So your final code could look something like this (this is pseudo-code):
matches; // this is set from previous code block
for(var i = 0; i < matches.length; i++) {
var needsToBeReplaced = matches[i][0];
var template = getTemplate(matches[i][1]);
}