ruwanego
ruwanego

Reputation: 427

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?

Upvotes: 9

Views: 15829

Answers (3)

Oskar Hane
Oskar Hane

Reputation: 1882

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

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

regexper

Image from Regexper.com

Upvotes: 4

falsetru
falsetru

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

Alnitak
Alnitak

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 independent

Upvotes: 13

Related Questions