Regex doesn't work as expected in javascript

I created a regex to test the name where only "_", "-", ",". "Are allowed.

Here's a regular expression:

^[a-zA-Z][a-zA-Z0-9\.\-_']{1,24}$

      

The problem is that this resolving name has @

, Check Demo screenshot :

var str = "deepak@";
var str2 = "@@";
alert(str.match("^[a-zA-Z][a-zA-Z0-9\.\-_]{1,24}$"));//allowing why?
alert(str2.match("^[a-zA-Z][a-zA-Z0-9\.\-_]{1,24}$"));//not allowing

      

Expected: The name having @

should not admit.

Note. When I checked this regex at https://regex101.com/#javascript it works well

+3


source to share


2 answers


Don't forget to use regex separator in Javascript:

alert(str.match(/^[a-zA-Z][a-zA-Z0-9\.\-_]{1,24}$/));

      

Or even better:



alert(str.match(/^[a-zA-Z][\w'.-]{1,24}$/));

      

Updated JSFiddle

+4


source


I think it would do the same:

str.match(/^\w{1,24}$/);

      



Definition:

The \ w metacharacter is used to search for a word character. Word character is a character from az, AZ, 0-9, including the _ (underscore) character.

-1


source







All Articles