Reputation: 4050
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})+[^/]$$/
Upvotes: 0
Views: 1621
Reputation: 147403
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\/]/;
Upvotes: 1
Reputation: 18522
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\-]$/
Upvotes: 3
Reputation: 20193
/
is a meta character in regex. You need to escape it with a backslash (\/
)
/^[^\/]([a-z0-9-]+[\/]{1})+[^\/]$/
Upvotes: 3