Question

So I'm just curious if there was a way to chain regexp. Just looking to optimize my code a little. I want to find an expression, then find another one from the results.

The Working Code:

match = $('body').html().match(/(\[~\{ .*? \}~\])/g);
console.log(match[0]);

findText = match[0].match(/\w+/);
console.log(findText);

What I've tried:

match = $('body').html().match(/(\[~\{ .*? \}~\])(\w+)/g);
console.log(match[0]);

produced an error

match = $('body').html().match(/(\[~\{ .*? \}~\])|(\w+)/g);
console.log(match[0]);

Found Expression 1 and then Found Expression 2 outside of expression 1.

My HTML:

[~{ header }~]

<p>This is the home page</p>

[~{ footer }~]
Was it helpful?

Solution

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.

Regex101


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

JSFiddle


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]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top