0

I would like to disallow double forward slashes (//) in my regular expression (and thus allow single /), but my solutions doesn't work.

There also has to be NO / at the beginning and ending of a string (this work!):

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

this allows for example example///example// but NOT/dzkoadokzd///zdkoazaz

Now I want to disallow multiple "/" after each other. I've tried this but it doesn't work (I'm new to regular expressions):

/^[^/]([a-z0-9-]+[/]{1})+[^/]$$/
1
  • It is called a forward slash or just slash. Backslash is \
    – kirilloid
    Mar 23, 2012 at 9:51

3 Answers 3

3

/ is a meta character in regex. You need to escape it with a backslash (\/)

/^[^\/]([a-z0-9-]+[\/]{1})+[^\/]$/
3
  • Thanks it's good to know! But this regular expression doesn't work (so does mine): it's invalidate text(a-z). Did you know where the error is? Thanks
    – benske
    Mar 23, 2012 at 9:06
  • 2
    This regex doesn't work, because it expects a single character after last "/". To fix it, add a "+" before the "$".
    – Rafael
    Mar 23, 2012 at 9:13
  • There is another potential problem with this regex. I expained everything in my answer.
    – Rafael
    Mar 23, 2012 at 9:22
3

Not sure if this is a requirement, but the regex from jperovic, by using [^/] will accept any character, which is not a slash / (so it will also pass strings like "@abcd/efgh/ijkl/#" (notice the @ and #), but in other parts of the regex we try to limit the characters to [a-z0-9-]. If we want to restrict the character range for the complete string, check the regex below.

/^[a-z0-9\-](?:[a-z0-9\-]|\/(?!\/))+[a-z0-9\-]$/
1
  • Perfect, it was indeed a problem! Thanks!
    – benske
    Mar 23, 2012 at 9:31
1

BTW, if you just want to test for slash at the start or end or double elsewhere:

function badSlash(s) {

  var re = /^\/|\/\/|\/$/;

  return re.test(s);
}

You can add another OR for whatever other patterns you don't want, e.g.

  var re = /^\/|\/\/|\/$|[^a-z0-9\/]/;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.