You need to append the global modifier, g
, to your regex: /[<](\S+).*>(.*)<\/\1>/g
.
If you don't use the g
global modifier, match
and exec
will return an array containing the whole first match in the string as the first element, followed by any parenthesised match patterns within the match as subsequent array elements.
If you do use the g
modifier, match
and exec
will get all the matches from the string. match
returns them as an array, and exec
will return one array for each match (with match patterns, as it does without g
) but multiple calls to exec
will each return a different match untill all matches have been reported (see below for an exmple).
In general, I would recommend match
over exec
, because exec
relies on the regular expression maintaining state (specifically, lastIndex
, the index of the string where the match should resume). I find this to be detrimental if you want to use a regular expression on multiple strings:
var reg = /\w/g;
reg.exec("foo"); // ["f"]
reg.exec("foo"); // ["o"]
reg.exec("bar"); // ["r"] -- does not start at the beginning of the string
Compare that to the match
behavior:
var reg = /\w/g;
"foo".match(reg); // ["f", "o", "o"]
"bar".match(reg); // ["b", "a", "r"]
// we can now use the arrays to get individual matches
However, if you need the get parenthesised match patterns for each match in a global search, you must use exec
, since global application of match
only gets a list of whole matches, not match patterns with those matches.
// the ending digit is a match pattern
var reg = /\w(\d)/g;
// match only gets list of whole matches
"d1b4h7".match(reg); // ["d1","b4","h7"]
// exec gets the match and the match pattern
reg.exec("d1b5h7"); // ["d1","1"]
reg.exec("d1b5h7"); // ["b4","4"]
reg.exec("d1b5h7"); // ["h7","7"]
In conclusion, it sounds like you want to use match
with a global modifier, since you don't need match pattern information. If you do actually need match pattern information, get all matches by using a loop to repeatedly call exec
, until exec
returns null
instead of an array.