0

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+\)/$');
if ( typeof s === 'string' && s.match(regex) )
    s = 'abc';
alert (s);

I have written a regex that I want to match strings that begin with the following exact characters: /Date( followed by one or more digits, followed by the exact characters )/ and nothing more.

In the above JavaScript code, I expect that the string 'abc' should be assigned to s, but at the conclusion of this code, the value of s is '/Date(1341118800000)/'.

How can I fix this?

3
  • Do you want to use abc when there is no match? Commented Jul 27, 2012 at 18:49
  • In this case, if the string s matches the regular expression, the string 'abc' should be assigned to s. Commented Jul 27, 2012 at 18:50
  • Why not just s = '/Date(1341118800000)/' == s ? "abc" : s; Commented Jul 27, 2012 at 19:08

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I tried your fix and it seems to work. However, I was following a "cheat sheet" here: addedbytes.com/download/regular-expressions-cheat-sheet-v2/png. The "cheat sheet" does not include / as a character that should be escaped. Is that an error on the cheat sheet, or is it specific to regex in JavaScript that / must be escaped?
@Daniel Allen Langdon: Is that sheet JavaScript specific? In JavaScript, regexp literals are enclosed by /, so you need to escape them if you want to use them literally. (The sheet also e.g. says > needs escaping but it doesn't in JavaScript.)
0

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+\\)/$');

Comments

0

I believe you are looking for this code:

var s = '/Date(1341118800000)/';
s = s.match(/^\/Date\((\d+)\)\/$/)[1];
alert(s);

Test it here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.