Trouble With JavaScript Regex Code To Match Characters And Numbers
I would like help with solving a problem using regular expressions. I've written the following JavaScript code: var s = '/Date(1341118800000)/'; var regex = new RegExp('^/Date\(\d+
Solution 1:
The escape slashes are already consumed by the string, i.e. "\(" === "("
. The resulting unescaped string is passed to new RegExp
, which interprets (
as a special character.
You should use a regular expression literal and escape the /
s as well:
var regex = /^\/Date\(\d+\)\/$/;
To test whether a string matches, you can use:
regex.test(s);
Solution 2:
The problem is that "/^/Date\(\d+\)/$/"
converts to "/^/Date(d+)/$/"
in javascript.
"/^/Date\(\d+\)/$/" == "/^/Date(d+)/$/" // returns true
So just escape the backspace, \
, to fix the problem.
var regex = new RegExp('^/Date\\(\\d+\\)/$');
Solution 3:
I believe you are looking for this code:
var s = '/Date(1341118800000)/';
s = s.match(/^\/Date\((\d+)\)\/$/)[1];
alert(s);
Test it here.
Post a Comment for "Trouble With JavaScript Regex Code To Match Characters And Numbers"