Doppelganger
Doppelganger

Reputation: 20855

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, but I have more requirements, if the example is not complete I'll edit and add whatever is necessary.

Upvotes: 2

Views: 103

Answers (1)

SLaks
SLaks

Reputation: 888283

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

Upvotes: 10

Related Questions