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.
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