I would like regex to match if and only if the string is none, family or work (but not my family, for example).
Why the following code results with “match” ? Why ^ and $ do not work ?
var regex = new RegExp("^none|family|work$");
var str = "my family";
document.write(regex.test(str) ? "match" : "no");
The
|operator has low precedence, so you effectively have(^none)|(family)|(work$), which matches anything beginning withnone, containingfamilyor ending withwork.Use this instead: