2

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.

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

nice +1. I know it was in the OP, but I don't think you need the i modifier with \w jsfiddle.net/cordsen/VQRPK

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.