Alex Rivera | Logout

JavaScript regular expression iterator to extract groups

Asked 2011-03-02T11:31:49.907
14

let's say we have the following text: "1 a,2 b,3 c,4 d" and the following expression: /\d (\w)/g

what we want to do is to extract a, b, c, d as denoted by the regular expression.

unfortunately "1 a,2 b,3 c,4 d".match(/\d (\w)/g) will produce an array: 1 a,2 b,3 c,4 d and RegExp.$1 will contain only the groups from the last match, i.e. RegExp.$1 == 'd'.

how can I iterate over this regex so that I can extract the groups as well... I am looking for a solution that is also memory efficient, i.e. some sort of iterator object

EDIT: It needs to be generic. I am only providing a simple example here. One solution is to loop over the array and reapply the regex for each item without the global flag but I find this solution a bit stupid although it seems to be like the only way to do it.

Edit
Report

1 Answer

2

This'll work:

"1 a,2 b,3 c,4 d".match(/\w(?:,|$)/g).join(' '); // => "a, b, c, d"

If you have a need to iterate:

var r = /\d (\w)/g,
    s = "1 a,2 b,3 c,4 d",
    m;

while ( m = r.exec(s) ) {
    // `m` is your match, `m[1]` is the letter
}
answered 2011-03-02T11:39:22.857

Your Answer