What's wrong with my Javascript regex?

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");

Answers


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)$");

Need Your Help

how to use substring function sqlite android

android sql sqlite

suppose I have a table name : TEST, that it has 2 columns ID and CONTENT, like this :

Read POP3 Email Account with SQL Server 2008

tsql sql-server-2008 email pop3

How can I read an accounts emails subject and content, and store these in my SQL Server database?