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

后端 未结 6 606
温柔的废话
温柔的废话 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:59

    I wrote a simple (well the initialization got a bit bloated) javascript object to solve this problem on a project I've been working on recently. It works the same way as the accepted answer but generates the new regexp and pulls out the data you requested automatically.

    var exp = new MultiRegExp(/(firstBit\w+)this text is ignored(optionalBit)?/i);
    var value = exp.exec("firstbitWithMorethis text is ignored");
    
    value = {0: {index: 0, text: 'firstbitWithMore'},
             1: null};
    

    Git Repo: My MultiRegExp. Hope this helps someone out there.

    edit Aug, 2015:

    Try me: MultiRegExp Live.

提交回复
热议问题