0

How can I write a proper regex for:

/Date(1518238800000)/ - matches

jdsjdsj - no match

2017/03/12 - no match

12 - no match

Date() - no match

/Date(1218238800000)/ - matches

What I have so far is:

var res = str.match(/Date(\d*)/g);

How can I amend the regex to work?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Jebathon
  • 4,310
  • 14
  • 57
  • 108

2 Answers2

1

I assume your string is a bit from a .NET serializer as mentioned here

How to parse ASP.NET JSON Date format with GWT

and

How to parse JSON to receive a Date object in JavaScript?

One of the answers have a reviver function you may want to use.

If not then the regex will need to have the parenthesis escaped:

var str = '{ "date": "/Date(1218238800000)/" }'
var re = /Date\((\d*)\)/g // escaping the () from the date and capture the number
res = re.exec(str);

console.log(res[1])

More dates and create date object:

var str = '{ "date1": "/Date(1218238800000)/", "date2": "/Date(1218248800000)/" }'
var re = /Date\((\d*)\)/g // escaping the () from the date and capture the number

while (res = re.exec(str)) {
  var date = +res[1]; // convert
  console.log(new Date(date)) 
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You need to escape the special characters like this:

let regex = /\/Date\(\d+\)\//g;
console.log(regex.test("/Date(123455)/"), //true
  regex.test("Date()"), //false
  regex.test("afdjkh"), //false
  regex.test("/Date(38457843)/")) //true
vityavv
  • 1,482
  • 12
  • 23