Is it possible to chain jQuery Regexp matches?

2019-05-30 16:48发布

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 }~]

1条回答
甜甜的少女心
2楼-- · 2019-05-30 17:30

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]);
}
查看更多
登录 后发表回答