Home > Net >  Regex to accept special character only in presence of alphabets or numeric value in JavaScript?
Regex to accept special character only in presence of alphabets or numeric value in JavaScript?

Time:11-17

I have a Javascript regex like this:

/^[a-zA-Z0-9 !@#$%^&*()-_-~. ,/\" ] $/

which allows following conditions:

  1. only alphabets allowed

  2. only numeric allowed

  3. combination of alphabets and numeric allowed

  4. combination of alphabets, numeric and special characters are allowed

I want to modify above regex with also cover one more case as below

only special characters are not allowed

string should not start with special characters

can someone please help me with this?

CodePudding user response:

You can require at least one alphanumeric:

/^(?=[^a-zA-Z0-9]*[a-zA-Z0-9])[a-zA-Z0-9 !@#$%^&*()_~. ,/\" -] $/
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Also, I think you wanted to match a literal -, so need to repeat it, just escape, change -_- to \-_, or - better - move to the end of the character class.

The (?=[^a-zA-Z0-9]*[a-zA-Z0-9]) pattern is a positive character class that requires an ASCII letter of digit after any zero or more chars other than ASCII letters or digits, immediately to the right of the current location, here, from the start of string.

  • Related