is not direct way in js to iterate a global regex and obtain the location of each group match in the input. This is kind of straight forward solution using indexOf and sum
A Pen by Sebastián Gurin on CodePen.
is not direct way in js to iterate a global regex and obtain the location of each group match in the input. This is kind of straight forward solution using indexOf and sum
A Pen by Sebastián Gurin on CodePen.
| !function () { | |
| const regex = /\/\*\*\*@\s*([^@]+)\s*(@\*\*\*\/)/gim | |
| const exampleThatMatch = ` | |
| /***@ | |
| debug.print('hello editor, simpleNode kind is ' + | |
| arg.simpleNode.getKindName()) | |
| @***/ | |
| const a = 1 //user | |
| /***@ | |
| debug.print(arg.simpleNode.getParent().getKindName()) | |
| @***/ | |
| ` | |
| const text = exampleThatMatch | |
| function exec(r, s) { | |
| function indexOfGroup(match, n) { | |
| var ix = match.index; | |
| for (var i = 1; i < n; i++) | |
| ix += match[i].length; | |
| return ix; | |
| } | |
| let result | |
| let lastMatchIndex = 0 | |
| const matches = [] | |
| while ((result = regex.exec(text))) { | |
| const match = [] | |
| lastMatchIndex = text.indexOf(result[0], lastMatchIndex) | |
| let relIndex = 0 | |
| for (let i = 1; i < result.length; i++) { | |
| relIndex = text.indexOf(result[i], relIndex) | |
| match.push({ value: result[i], start: relIndex, end: relIndex + result[i].length }) | |
| } | |
| matches.push(match) | |
| } | |
| return matches | |
| } | |
| const groupsWithIndex = exec(regex, text) | |
| console.log({RESULT: groupsWithIndex }) | |
| // now test - let's remove everything else but matched groups | |
| let frag = '' , sep = '\n#######\n' | |
| groupsWithIndex.forEach(match => match.forEach(group => { | |
| frag += text.substring(group.start, group.end) + sep | |
| })) | |
| console.log('The following are only the matched groups usign the result and text.substring just to verify it works OK:', '\n'+sep) | |
| console.log(frag) | |
| }() | |