简体   繁体   中英

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

The escape slashes are already consumed by the string, ie "\\(" === "(" . 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);

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

I believe you are looking for this code:

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

Test it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM