Reputation: 4323
According to the documentation, String.prototype.match()
must return all matches of a regular expression in a string. However,
"Foo 09:00 bar 21-00 foobar".match(/\d{2}[:\-]\d{2}/)
returns only ["09:00"]
, whereas the expected result is ["09:00", "21:00"]
. Why?
By the way,
"Foo 09:00 bar 21-00 foobar".split(/\d{2}[:\-]\d{2}/)
returns ["Foo ", " bar ", " foobar"]
, which means 21-00
is matched by the regular expression.
Upvotes: 0
Views: 78
Reputation: 59232
You are missing g
(global) modifier. Use it.
If you don't, it will stop at the first match.
Like this:
"Foo 09:00 bar 21-00 foobar".match(/\d{2}[:-]\d{2}/g)
Also, you don't need to escape -
if it is at the starting or at the end of character class.
The MDN document which you referred also says:
- returns the same result as RegExp.exec(str) [i.e. the captured groups, index, etc] if the regular expression does not include the
g
flag- returns an Array containing all matches if the regular expression includes the g flag
Upvotes: 5
Reputation: 664513
According to the documentation, String.prototype.match()
- returns the same result as
RegExp.exec(str)
[i.e. the captured groups, index, etc] if the regular expression does not include theg
flag- returns an Array containing all matches if the regular expression includes the
g
flag
> "Foo 09:00 bar 21-00 foobar".match(/\d{2}[:\-]\d{2}/)
Array ["09:00", index:4, input:"Foo 09:00 bar 21-00 foobar"]
> "Foo 09:00 bar 21-00 foobar".match(/\d{2}[:\-]\d{2}/g)
Array ["09:00", "21-00"]
Upvotes: 3