Need a JavaScript regular expression for validating a string that should start with a forward slash ("/") followed by alphanumeric characters with no spaces?
You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex.
Some languages use / as the pattern delimiter, so yes, you need to escape it, depending on which language/context.
The RegExp \D Metacharacter in JavaScript is used to search non digit characters i.e all the characters except digits. It is same as [^0-9]. Example 1: This example searches the non-digit characters in the whole string.
A slash. A slash symbol '/' is not a special character, but in JavaScript it is used to open and close the regexp: /... pattern.../ , so we should escape it too.
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 independentThis should do it. This takes a-z and A-Z and 0-9.
/^\/[a-z0-9]+$/i
Image from Regexper.com
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
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