0

I have a line like this:

\/Date(1475832958000)\/

I would like to extract a number from it. I did so:

var regex = /(\d+)/;
var str = '\/Date(1475832958000)\/';
console.log(str.match(regex));
//["1475832958000", "1475832958000"]

I get an array of 2 elements. I do not understand why. Please, help.

Sergey Sigaev
  • 100
  • 2
  • 10

2 Answers2

2

In the regex () is using for capturing group, the first element is the complete match and the second one is the captured value.

From MDN docs :

An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.


If you want to get the number only within the bracket then escape the parenthesis(by adding backslash, \).

var regex = /\(\d+\)/;
var str = '\/Date(1475832958000)\/';
console.log(str.match(regex));

// or in case you just want to get the number 
// then use capturing group
var regex1 = /\((\d+)\)/;
console.log(str.match(regex1));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875