Because the ()
in your regular expression define a capture group. match
returns an array with the match for the overall regular expression in position 0, followed by whatever matched within capture groups as subsequent entries.
You probably wanted the regex to be /^\/Date\((\d+)\)\/$/
, and to use the result at [1]
as a number:
var str = '/Date(1475832958000)/';
var rex = /^\/Date\((\d+)\)\/$/;
var result = str.match(rex);
if (result) {
var num = result ? +result[1] : null;
console.log("Number: " + num);
var dt = new Date(num);
console.log("Date: " + dt.toString());
}
The regex /^\/Date\((\d+)\)\/$/
means:
^
- Start of input
\/Date\(
- The literal text /Date(
. We have to escape the /
because otherwise it terminates the regular expression, and we have to escape the (
so it's a literal (
rather than starting a capture group.
(\d+)
- A capture group capturing one or more digits.
\)\/
- The literal text )/
.
$
- End of input
Side note: The \/
s in your string literal '\/Date(1475832958000)\/'
are just /
s, no need for the backslash on them. '\/Date(1475832958000)\/'
and '/Date(1475832958000)/'
are the exact same string.