[英]determine if a path is relative or absolute
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 顺便说一句,我意识到//google.com
在技术上是相对的,但是我仍然不想匹配这种情况
I need this to be able to tell if I need to deal with a link after a pushState. 我需要它来告诉我是否需要处理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
考虑一下,如果我从/
开始,然后将pushState
d转到/page1/
则具有href为'index2.html'
的链接应该转到/index2.html
但现在将转到/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. 不要使用诸如regexp等低级的东西。这些东西已经被很多其他人解决了。 Especially the edge cases. 尤其是边缘情况。
Have a look at URI.js , it should do the job: http://medialize.github.io/URI.js/docs.html#is 看一下URI.js ,它应该可以完成工作: 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
. 所提及的解决方案均未解决骇客输入/\\/example.com
或/\\\\/example.com
的redirect_url
骇客。 This is what I came up with to determine if our redirect url was relative: 这是我想出的方法,以确定我们的重定向URL是否是相对的:
var isRelative = !redirectUrl.match(/(\:|\/\\*\/)/); // Don't allow "//" (with optional "\"'s) or ":"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.