views:

29

answers:

2

I'm getting different behavior from a regular expression in JavaScript depending on whether or not I declare it using literal syntax. Using a extremely simple test HTML file:

<html>
    <head>
        <script type="text/javascript">
            var s = '3';
            var regex1 = /\d/;
            var regex2 = new RegExp('\d');

            alert(s.search(regex1)); //  0 (matches)
            alert(s.search(regex2)); // -1 (does not match)
        </script>
    </head>
    <body></body>
</html>

The regular expression declared with literal syntax (/\d/) works correctly, while the other (new RegExp('\d')) does not. Why on earth is this happening?

I'm using Google Chrome 5.0.375.70 on Windows Vista Home Premium, if that's at all helpful.

A: 
var regex2 = new RegExp('\\d');

works for me.

RC
+2  A: 

If using strings, \d is a special character. You need to escape the backslash:

var regex2 = new RegExp('\\d');

See String Literals:

Escaping Characters

For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

So basically '\d' is treated as 'd', which is why it doesn't match. For example:

alert('d'.search(new RegExp('\d'))); // 0 (matches!)
cletus
Thanks very much!
Kiwi