Reputation: 427
Need a JavaScript regular expression for validating a string that should start with a forward slash ("/") followed by alphanumeric characters with no spaces?
Upvotes: 9
Views: 15829
Reputation: 1882
This should do it. This takes a-z and A-Z and 0-9.
/^\/[a-z0-9]+$/i
Image from Regexper.com
Upvotes: 4
Reputation: 369084
Try following:
/^\/[\da-z]+$/i.test('/123') // true
/^\/[\da-z]+$/i.test('/blah') // true
/^\/[\da-z]+$/i.test('/bl ah') // false
/^\/[\da-z]+$/i.test('/') // false
Upvotes: 1
Reputation: 339816
The regex you need is:
/^\/[a-z0-9]+$/i
i.e.:
^
- anchor the start of the string\/
- a literal forward slash, escaped[a-z0-9]+
- 1 or more letters or digits. You can also use \d
instead of 0-9
$
- up to the end of the string/i
- case independentUpvotes: 13