user4913383 user4913383 - 2 months ago 18
Javascript Question

Why does "ab".match(/ab/) returns ["ab","ab"]?

Why does following:


"ab".match(/(ab)/);


returns this:


["ab", "ab"]


Though "ab" appears once in the string "ab" , why has "ab" appeared twice in the array?

Answer

The first element contains the entire matching string, while the next elements contain the group matches. Consider:

> "somestring44".match(/[a-z]([a-z]*)/)
["somestring", "omestring"]