Skip to content

Instantly share code, notes, and snippets.

@Rycochet
Last active January 4, 2016 08:48
Show Gist options
  • Save Rycochet/8597361 to your computer and use it in GitHub Desktop.
Save Rycochet/8597361 to your computer and use it in GitHub Desktop.
Split a string into an array of regex matches, or a single result if only a single match
/**
* Split a string into an array of regex matches, or a single result if only a single match
* @param {RegExp} r The pattern to check against
* @return {Array|string|number} The matches
*/
String.prototype.regex = function(r) {
var a = this.match(r), i, rx;
if (a) {
if (r.global) {
if (/(^|[^\\]|[^\\](\\\\)*)\([^?]/.test(r.source)) { // Try to match "(blah" but not "\(blah" or "(?:blah" - ignore invalid regexp
rx = new RegExp(r.source, (r.ignoreCase ? "i" : "") + (r.multiline ? "m" : ""));
}
} else {
a.shift();
}
i = a.length;
while (i--) {
if (a[i]) {
if (rx) {
a[i] = a[i].regex(rx);
} else {
if (a[i].search(/^[\-+]?\d*\.?\d+(?:e[\-+]?\d+)?$/i) >= 0) {
a[i] = parseFloat(a[i]);
}
}
}
}
if (!rx && a.length === 1) {
return a[0];
}
}
return a;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment