Regex multiple matching with exec via http://stackoverflow.com/a/2295943/2668831
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
myre = /]\(/g | |
mystr = 'hello ]( world ]( i ]( said ](' | |
while ((match = myre.exec(mystr)) != null) { | |
console.log(myre.lastIndex) | |
} | |
/* | |
8 | |
17 | |
22 | |
30 | |
*/ | |
while ((match = myre.exec(mystr)) != null) { | |
console.log(match.index + match[0].length) | |
} | |
/* | |
8 | |
17 | |
22 | |
30 | |
*/ | |
// mystr.length | |
// 30 | |
/* Note that if assigning a value, repeated overwriting lets you use the last output of the loop | |
- can be handy, e.g. find the definitive separator in a markdown link: */ | |
var mylink = "![hello ]( world ]( i ]( said ](https://gist.github.com)" | |
// strip off ![ and ), so start from character 2 and end 3 characters shorter than length | |
var link_inner = mylink.substr(2, mylink.length - 3); | |
while ((match = myre.exec(link_inner)) != null) { | |
var link_sep = myre.lastIndex; | |
} | |
matchstring = '](' // for reference | |
var link_alt = link_inner.substring(0, link_sep - matchstring.length); | |
// "hello ]( world ]( i ]( said " | |
var link_href = link_inner.substring(link_sep); | |
// "https://gist.github.com" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment