I am trying to created a regular expression to validate a Url path. I have come up with this:
^\/([a-zA-Z0-9\-]+)?$
Which allows me the have /
or /moo
or a more complex /products-123
but it doesn't allow me to use multiple forward slashes like /blog/posts-123
.
Can someone help me with this?
Ideally it should be able to allow:
If someone could help me with this, it would be great
This regex allows
let urls = [
'/',
'/aaa-bbb',
'/aaa-bbb/ccc',
'/aaa-bbb/ccc/ddd',
'/aaa-bbb/ccc/ddd/eee',
'', // empty
'//double-slash',
'/end-with-slash/',
];
let regex = /^(\/|(\/[a-zA-Z0-9\-]+)+)$/;
urls.forEach((url) => {
let result = regex.test(url);
console.log('"' + url + '" ==> ' + result);
});
Result:
"/" ==> true
"/aaa-bbb" ==> true
"/aaa-bbb/ccc" ==> true
"/aaa-bbb/ccc/ddd" ==> true
"/aaa-bbb/ccc/ddd/eee" ==> true
"" ==> false
"//double-slash" ==> false
"/end-with-slash/" ==> false
As you can see from the result, it guards against an empty url path, a url path with double slashes, and a url path ending in a slash.
Explanation of regex:
^(\/|(...)+)$
- expect a single slash, or a 1+ sequence in parenthesis\/[a-zA-Z0-9\-]+$
- sequence in parenthesis is a slash, followed by one or more chars of alphanumeric and dash