Is there a simple regex to determine if a path is relative, or a hash?
I want to match these:
../index.php
js/funct.js
./home/
php/file.php?url=http://www.google.com
index.html#about=http://www.google.com
but not these:
http://www.google.com
http://google.com
/index.php
/
//google.com
#div4
here's what I have so far:
/^[^#\/]|\/\//.test(url)
But it's not working. Is there any way to get this to work?
btw I realize that //google.com
is technically relative but I still don't want to match that case
I need this to be able to tell if I need to deal with a link after a pushState. Consider if I started on /
and then pushState
d to /page1/
then a link that has a href of 'index2.html'
was supposed to go to /index2.html
but will now go to /page1/index2.html
So I need to check for those types of relative paths.
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js , it should do the job: http://medialize.github.io/URI.js/docs.html#is
var uri = new URI("/example.org/");
uri.is("relative") === true;
It should not start with a slash or hash, and it should not contain a double slash if not preceded by question mark or hash? I would not test that with a single regexp, it would be very complicated to match "no double slash".
function test(s) {
return s.charAt(0) != "#"
&& s.charAt(0) != "/"
&& ( s.indexOf("//") == -1
|| s.indexOf("//") > s.indexOf("#")
|| s.indexOf("//") > s.indexOf("?")
);
}
would be easier, clearer and imho faster.
Neither of the mentioned solutions solved a redirect_url
hack where the hacker entered /\\/example.com
or /\\\\/example.com
. This is what I came up with to determine if our redirect url was relative:
var isRelative = !redirectUrl.match(/(\:|\/\\*\/)/); // Don't allow "//" (with optional "\"'s) or ":"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.