jquery - 获取 url 路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2668005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery - get url path?
提问by KittyYoung
I know I can use window.location.pathname to return a url, but how do I parse the url?
我知道我可以使用 window.location.pathname 来返回一个 url,但是我如何解析这个 url?
I have a url like this: http://localhost/messages/mine/9889and I'm trying to check to see if "mine" exists in that url?
我有一个这样的网址:http://localhost/messages/mine/9889,我试图检查该网址中是否存在“我的”?
So, if "mine" is the second piece in that url, I want to write an if statement based on that...
因此,如果“我的”是该 url 中的第二部分,我想根据它编写一个 if 语句......
if(second argument == 'mine') { do something }
回答by Mario Menger
if ( location.pathname.split("/")[2] == "mine" ) { do something }
Although it would obviously be better to check whether there are enough items in the array that's returned by split:
尽管检查 split 返回的数组中是否有足够的项目显然会更好:
var a = location.pathname.split("/");
if ( a.length > 2 && a[2] == "mine" ) { do something }
Note that even though array indexes are zero based, we want to specify 2 as the index to get what you refer to as the 2nd argument as split splits "/messages/mine/9889" into an array of 4 items:
请注意,即使数组索引是从零开始的,我们也希望指定 2 作为索引以获得您所说的第二个参数,因为 split 将“/messages/mine/9889”拆分为 4 个项目的数组:
["", "messages", "mine", "9889"]
回答by derek
if jquery is an option, you could do the following:
如果 jquery 是一个选项,您可以执行以下操作:
$.inArray("mine", window.location.pathname.split("/"))
回答by Matt
if (window.location.pathname.split("/")[2] == "mine") {
// it exists
};
window.location.pathname is a string at the end of the day, so the usual string methodsapply.
回答by Jiju Thomas Mathew
Even though this is a very old query.. it pops up in some search. So to add my notes.. over here
尽管这是一个非常古老的查询......它会在某些搜索中弹出。所以添加我的笔记..在这里
url.indexOf('mine') !== -1
The above should be used for the check to find if url has a string... where as to find the path, it would be better off to use
上面应该用于检查以查找 url 是否有字符串......至于找到路径,最好使用
var a = document.createElement('a');
a.href = url;
console.log(a.pathname);
// if url='http://localhost/messages/mine/9889'
// output will be /messages/mine/9889
hope this will save some ones time
希望这会节省一些时间
回答by James Westgate
You could use the string.split('/') function to create an array of items to check otherwise there are several jQuery plugins that parse the url eg
您可以使用 string.split('/') 函数创建一个项目数组来检查,否则有几个 jQuery 插件可以解析 url,例如