Created
December 4, 2009 02:42
-
-
Save brianpeiris/248791 to your computer and use it in GitHub Desktop.
String RegExp matches function
This file contains hidden or 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
/*** | |
The matches function, similar to String.match(), | |
returns an array of sub-groups captured by the given RegExp. | |
***/ | |
function matches(string, regexp, position, result) { | |
position = position || 0; | |
result = result || []; | |
var match = string.slice(position).match(regexp); | |
if (match === null) { | |
return result; | |
} | |
else { | |
match.index = position + match.index; | |
match.input = string; | |
result.push(match) | |
return matches(string, regexp, match.index + match[0].length, result); | |
} | |
} | |
/*** | |
Optionally add the matches function to the String prototype. | |
***/ | |
/* | |
String.prototype.matches = function (regexp, position) { | |
return matches(this.toString(), regexp, position); | |
}; | |
*/ | |
var | |
log = console.log, | |
assert = console.assert; | |
var | |
testString = 'fooABbar fOoC1bar bazEFbar FooGHbar fooIjbar'; | |
expectedMatches = [ | |
{'0': 'fooABbar', '1': 'A', '2': 'B', index: 0, input: testString}, | |
{'0': 'FooGHbar', '1': 'G', '2': 'H', index: 27, input: testString}, | |
{'0': 'fooIjbar', '1': 'I', '2': 'j', index: 36, input: testString}, | |
], | |
actualMatches = matches(testString, /foo([a-z])([a-z])bar/i); | |
for (var ii = 0; ii < expectedMatches.length; ii++) { | |
for (var key in expectedMatches[ii]) { | |
assert(expectedMatches[ii][key] === actualMatches[ii][key]); | |
} | |
} | |
log("Test passed"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment