开发者

Can't get javascript length-related regex to work

I'm trying to write a Javascript regex that matches words with less than 3 letters (and doesn't match longer words). I can't see why this doesn't work.

<html>
        <body>
                <script>
                var re = new RegExp("(\W|^)\w{0,2}(\W|$)", "gi");
                var text = "ab ab";
                var matched = re.test(text);
                document.write(matched)

                </script>
        </body>
</html>

I tried to get a minimum example, 开发者_JS百科but I have more requirements, if the example is not complete I'll edit and add whatever is necessary.


Your \s are being treated as Javascript escapes, so the actual value of the regex is "(W|^)w{0,2}(W|$)".

Instead, use a regex literal: /(\W|^)\w{0,2}(\W|$)/gi

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜