This is a regex where string must start and end with an alphanumeric character and can contain alphanumeric characters and dashes.
/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-]+[a-zA-Z0-9]{1}$/
How can I make sure that the consecutive dashes are not allowed? for example:
should allow: some-string
should NOT allow: some--string
Thanks
Edit: I want to allow several dashes, just not consecutively. for example "some-thing-here" is OK, and "some--thing" is NOT.
No need for complicated patterns with optional dashes just use this:
/^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$/
See it here on Regexr
Start with at least one alphanumeric. Then there can be a dash followed by at least one alphanumerics 0 ore more times.
Something like:
/^[a-zA-Z0-9]{1}\-?([a-zA-Z0-9]+\-?)*[a-zA-Z0-9]{1}$/
The key part being \-?([a-zA-Z0-9]+\-?)* which makes it read "a letter/number, optional dash, any amount of (some letters/numbers, optionally followed by a dash), ending in a letter or number."
This allows some-string, my-double-dash-string but not my-double--dash-string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With