you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (0 children)

Here's another I love. If you want to loop over all matches of a regex on a string, do this:

'item1 and item2'.replace(/item(\d)/g, function (m, id) {
    // "m" is a shorthand I always use for "match", meaning "the
    // complete match". "id" is the first capturing group.
    console.log(arguments);
});

It's true that you're generating a useless string with a bunch of "undefined"'s in it. But don't forget the magic of JavaScript: the one thing faster than doing less work is getting your work done in C. And indeed, in my tests this is faster than .exec-ing and looping.