On Sun, Oct 23, 2011 at 10:41 AM, pete otaqui <p...@otaqui.com> wrote: > Regular Expressions in Javascript don't make it easy to capture sub patterns > when operating globally (i.e. using the 'g' modifier). > snip... > > So are we stuck? Do we need to use two separate string manipulation > routines? No: we can use "replace" with a callback (and not do any actual > replacing). Consider the following: snip... > > We don't need to return anything from the callback, since neither are we > assigning the return from string.replace to anything - but this is the only > apparent method of looping through a global regexp with sub patterns.
Ok, I hope I'm reading your mail/question properly, but I think you're trying to get all matches of a global regexp. If so, good news! It can be done. If not, well, then please clarify your actual question or hope somebody else does get it ;) So regexp objects have this property called `lastIndex`. It's basically only useful for global regexes, but will exist nonetheless. The beauty about this property is that it's actually taken into account when applying a global regexp to a string. Because it will actually start matching at `lastIndex`. So rather than the replace function (which is ok, unless you're doing some serious searching or need to stop after n matches) you could just loop it through. var match = null; var matches = []; var r = /(ab)b/g; var s = 'aaabbabaaabbabababbaaabbab'; while (match = r.exec(s)) { matches.push(match); } Oh and these match objects should have an `index` property that tell you the start of the match. Of course this is a simple example where it doesn't really make sense to actually save the matches like that, but you probably want to apply it to a regex and string where the results are not as predictable. - peter -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/jsmentors@jsmentors.com/ To search via a non-Google archive, visit here: http://www.mail-archive.com/jsmentors@googlegroups.com/ To unsubscribe from this group, send email to jsmentors+unsubscr...@googlegroups.com