How to find indices of groups in JavaScript regular expressions match?

后端 未结 6 605
温柔的废话
温柔的废话 2020-12-09 09:33

When I write a regular expression like:

var m = /(s+).*?(l)[^l]*?(o+)/.exec(\"this is hello to you\");
console.log(m);

I get a match object

6条回答
  •  失恋的感觉
    2020-12-09 09:46

    You can't directly get the index of a match group. What you have to do is first put every character in a match group, even the ones you don't care about:

    var m= /(s+)(.*?)(l)([^l]*?)(o+)/.exec('this is hello to you');
    

    Now you've got the whole match in parts:

    ['s is hello', 's', ' is hel', 'l', '', 'o']
    

    So you can add up the lengths of the strings before your group to get the offset from the match index to the group index:

    function indexOfGroup(match, n) {
        var ix= match.index;
        for (var i= 1; i

提交回复
热议问题