In Javascript ,why
/^(\d{1}){3}$/.exec(123)
returns ["123", "3"]
, but
/^(\d{1})$/.exec(123)
returns null
rather than ["3"]
.
Also, why is the first expression returning 3
, when 1
is the digit that follows ^
?
In Javascript ,why
/^(\d{1}){3}$/.exec(123)
returns ["123", "3"]
, but
/^(\d{1})$/.exec(123)
returns null
rather than ["3"]
.
Also, why is the first expression returning 3
, when 1
is the digit that follows ^
?
Noting that \d{1}
is equivalent to just \d
,
/^(\d{1}){3}$/
can be simplified to
/^(\d){3}$/
which means
The parenthesis around \d
define a capture group. As explained here and here, when you repeat a capturing group, the usual implementation keeps only the last capture.
That's why the final result is
[
"123", // the whole matched string
"3", // the last captured group
]
/^(\d{1})$/
can again be simplified to
/^(\d)$/
which means
Being 123
a three-digit string, it's not matched by the regex, so the result is null
.