Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex for string starting with forward slash followed by alphanum chars and no space

Need a JavaScript regular expression for validating a string that should start with a forward slash ("/") followed by alphanumeric characters with no spaces?

like image 943
ruwanego Avatar asked Sep 13 '13 07:09

ruwanego


People also ask

How do you handle forward slash in regex?

You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex.

Do I need to escape forward slash in regex?

Some languages use / as the pattern delimiter, so yes, you need to escape it, depending on which language/context.

What is \d in JavaScript regex?

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.

Does forward slash need to be escaped in JavaScript?

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.


3 Answers

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 independent
like image 155
Alnitak Avatar answered Sep 30 '22 17:09

Alnitak


This should do it. This takes a-z and A-Z and 0-9.

/^\/[a-z0-9]+$/i

regexper

Image from Regexper.com

like image 38
Oskar Hane Avatar answered Sep 30 '22 16:09

Oskar Hane


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
like image 31
falsetru Avatar answered Sep 30 '22 16:09

falsetru