I recently released some useful additions to String.prototype
over on Github (linky). One of the more useful methods in there is extract
. I’m sure something similar to this already exists but I’ve yet to find it.
It’s useful when you need to extract a particular group of every match from a global regular expression. Normally you’d have to use the RegExp.exec
method along with a while loop to extract that info, and, that is exactly what’s going on behind the scenes. Have a look:
The code:
String.prototype.extract = function( regex, n ) { n = n === undefined ? 0 : n; if ( !regex.global ) { return this.match(regex)[n] || ''; } var match, extracted = []; while ( (match = regex.exec(this)) ) { extracted[extracted.length] = match[n] || ''; } return extracted; }; |
Example:
('hi @rob and @adam, oh and @bob').extract(/@(w+)/g, 1); // => ['rob', 'adam', 'bob'] |
(With the above example, you could achieve it with a simple match()
if JavaScript supported look-behinds…)
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
I did this recently, which is sort of the reverse of your extract method
hi,Pete, I think there is something wrong in your code, so I just modified it and it works now: