开发者

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 regula开发者_开发知识库r 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.


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


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

works for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜