Skip to content

Instantly share code, notes, and snippets.

@lmmx
Last active August 29, 2015 14:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lmmx/eddf11da4236057c89e5 to your computer and use it in GitHub Desktop.
Regex multiple matching with exec via http://stackoverflow.com/a/2295943/2668831
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