Created
November 16, 2015 21:03
-
-
Save TooTallNate/34a2e8124571c93422ff to your computer and use it in GitHub Desktop.
for (let match of /foo/g.exec('foo bar baz')) console.log(match);
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
require('./MatchIterator'); | |
// if we want to be bad… | |
String.prototype.match = (function (match) { | |
return function (regexp) { | |
var m = match.apply(this, arguments); | |
if (m) m[Symbol.iterator] = () => MatchIterator(this, regexp, regexp.global ? null : m); | |
return m; | |
}; | |
})(String.prototype.match); | |
RegExp.prototype.exec = (function (exec) { | |
return function (str) { | |
var m = exec.apply(this, arguments); | |
if (m) m[Symbol.iterator] = () => MatchIterator(str, this, m); | |
return m; | |
}; | |
})(RegExp.prototype.exec); |
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
function *MatchIterator (string, regexp, match) { | |
if (match) yield match; | |
match = regexp.exec(string); | |
while (match != null) { | |
yield match; | |
match = regexp.exec(string); | |
} | |
}; | |
module.exports = MatchIterator; |
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
require('./extend'); | |
var iterator; | |
iterator = 'foo bar baz'.match(/\bba\w\b/g); | |
console.log('match iterator', iterator); | |
// match iterator [ 'bar', 'baz' ] | |
console.log([...iterator]); | |
// [ [ 'bar', index: 4, input: 'foo bar baz' ], | |
// [ 'baz', index: 8, input: 'foo bar baz' ] ] | |
iterator = /\bba\w\b/g.exec('foo bar baz'); | |
console.log('exec iterator', iterator); | |
// exec iterator [ 'bar', index: 4, input: 'foo bar baz' ] | |
console.log([...iterator]); | |
// [ [ 'bar', index: 4, input: 'foo bar baz' ], | |
// [ 'baz', index: 8, input: 'foo bar baz' ] ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment