I would like to test if user type only alphanumeric value or one \"-\".
hello-world -> Match
hello-first-world -> match
this-
I'm not entirely sure if this works because I haven't done regex in awhile, but it sounds like you need the following:
/^[A-Za-z0-9]+(-[A-Za-z0-9]+)+$/
You're requirement is split up in the following:
I'm just not sure if I did the regex properly to follow that format.
(^-)|-{2,}|[^a-zA-Z-]|(-$)
looks for invalid characters, so zero matches to that pattern would satisfy your requirement.
Here you go (this works).
var regExp = /^[A-Za-z0-9]+([-]{1}[A-Za-z0-9]+)+$/;
letters and numbers greedy, single dash, repeat this combination, end with letters and numbers.
Try this:
/^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/
This will only match sequences of one or more sequences of alphanumeric characters separated by a single -
. If you do not want to allow single words (e.g. just hello
), replace the *
multiplier with +
to allow only one or more repetitions of the last group.