开发者

Can't get javascript length-related regex to work

开发者 https://www.devze.com 2023-03-16 10:38 出处:网络
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.

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

精彩评论

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