@Valentino, that looks like a very useful tool, thank you!
@Luke, thank you for the suggestions! I had no idea exec and match behaved differently. I’ll add that to the post. Also, just subscribed to http://blog.stevenlevithan.com/ – looks great!
Correction: str.match and regex.exec are only the same if the regex is not compiled with the g flag. Against a g regex, match does not return capture groups, but every instance of the full match. exec returns the first match and any capture groups and updates the regex’s lastIndex Property. Future calls to exec will start from that index (useful in a while loop).
var re = /f(w)1/g, str = "Calling all foo, calling all faa"; str.match(re); // ["foo","faa"] str.match(re); // ["foo","faa"] re.exec(str); // ["foo","o"] and re.lastIndex === 15 re.exec(str); // ["faa","a"] and re.lastIndex === 32 |
Suggestions:
Unless you specifically need the data in your groups, use a non-capturing group, vis /(?:f|ht)tps?/ won’t internally store or return the f or ht string. It makes for marginally faster code, but more importantly, you don’t have to specify unused variables for dead captures if you have important capture groups afterward.
And your camelCaseCSS function doesn’t need an inner regex. charAt(1) will do the work much faster.
function camelCaseCSS(property) { return property.replace(/-w/g, function(match){ return match.charAt(1).toUpperCase(); }); } |
Another great resource for advanced regex know-how is Steven Levithan’s blog Flagrant Badassery http://blog.stevenlevithan.com/
]]>When I started using it, creating regular expressions became actually fun!
]]>i dug up an old regex i had for this, and seems completely bloated compared to your. great work.
here is my old one (stripped from a class)
// site Site:function() { var pattern = /^(([f]|[h])(t?tp)(s?)(://))?((www)(.))?/; var site = window.content.location.host; site = site.replace(pattern, ''); return site; } |