开发者

What's wrong with my Javascript regex?

开发者 https://www.devze.com 2023-01-13 04:40 出处:网络
I would like regex to match if and only if the string is none, family or work (but not my family开发者_运维知识库, for example).

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 with none, containing family or ending with work.

Use this instead:

^(none|family|work)$


Your regex matches either:

  • “none” at the beginning of the string;
  • “family” anywhere in the string; or
  • “work” at the end of the string.

What you probably want instead is

var regex = new RegExp("^(none|family|work)$");
0

精彩评论

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