Kiwi
Kiwi

Reputation: 1093

Strange JavaScript Regular Expression Behavior

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.

Upvotes: 1

Views: 125

Answers (2)

cletus
cletus

Reputation: 625037

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!)

Upvotes: 2

user180100
user180100

Reputation:

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

works for me.

Upvotes: 0

Related Questions