Reputation: 83
how to make regular expression when user enter first character is dash(-) it can't allow(user can enter alpha or numeric AS a first character)
but then after 2nd characters onward user can enter alpha,numeric and dash(-)
Upvotes: 1
Views: 2633
Reputation: 128836
A regular expression might be a bit expensive here. You can simply use charAt(0)
to grab the first character from your string, then check to see whether it's the "-"
character like so:
var myString = ...
if (myString.charAt(0) === "-")
// Do this if true
else
// Do this if false
but then after 2nd characters onward user can enter alpha,numeric and dash(-)
If this, however, means that any characters after the first dash character must be alphanumeric or a dash character, you'd need to use the following regular expression:
/^-[a-zA-Z0-9\-]+$/
Like so:
/^-[a-zA-Z0-9\-]+$/.test(myString);
Here's a Regexper visualisation:
Upvotes: 2