Get index of each capture in a JavaScript regex

后端 未结 7 814
一个人的身影
一个人的身影 2020-11-29 04:43

I want to match a regex like /(a).(b)(c.)d/ with \"aabccde\", and get the following information back:

\"a\" at index = 0
\"b\" at i         


        
7条回答
  •  無奈伤痛
    2020-11-29 05:10

    With RegExp.prototype.exec() and searching the properly indexes of the result:

    let regex1 = /([a-z]+):([0-9]+)/g;
    let str1 = 'hello:123';
    let array1;
    let resultArray = []
    
    while ((array1 = regex1.exec(str1)) !== null) {
      const quantityFound = (Object.keys(array1).length - 3); // 3 default keys
      for (var i = 1; i

提交回复
热议问题