Rohit Verma Rohit Verma - 2 years ago 151
Javascript Question

Javascript Regular expression : ^[^/\s/]+[a-z]{1,}[0-9]*[\-\_]*[^\/][^/\s/]$

I want to create a regular expression which will:

  • not contain any space and special characters except "-" and "_"

  • it should contain at least one alphabet character

The regular expression I created is:


It only only matches if my string contains at least 4 characters, including 1 alphabet. I tried it on Can someone help me what I am doing wrong here.

Answer Source

You need to learn about lookaround. One solution to your problem is:

  • (?=^[\w-]{4,}$) will assert that you input will contains only chars in the range a-z, digit, _ and , - with a length of at least 4.
  • (.*[a-z].*) ensure that there will be at least one char in the range a-z.

See Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download