jquery - 获取url路径?

Kit*_*ung 18 url jquery parsing

我知道我可以使用window.location.pathname返回一个url,但是如何解析url?

我有一个这样的网址:http:// localhost/messages/mine/9889我正试图查看该网址中是否存在"我的"?

所以,如果"我的"是该网址的第二部分,我想写一个if语句基于...

if(second argument == 'mine') { do something }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ger 44

if ( location.pathname.split("/")[2] == "mine" ) { do something }
Run Code Online (Sandbox Code Playgroud)

虽然显然更好的方法是检查数组中是否有足够的项目由split返回:

var a = location.pathname.split("/");
if ( a.length > 2 && a[2] == "mine" ) { do something }
Run Code Online (Sandbox Code Playgroud)

请注意,即使数组索引基于零,我们也要指定2作为索引来获取您所引用的第二个参数,因为split将"/ messages/mine/9889"拆分为4个项目的数组:

["", "messages", "mine", "9889"]
Run Code Online (Sandbox Code Playgroud)


der*_*rek 8

如果jquery是一个选项,你可以执行以下操作:

$.inArray("mine", window.location.pathname.split("/"))
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 5

if (window.location.pathname.split("/")[2] == "mine") {
  // it exists
};
Run Code Online (Sandbox Code Playgroud)

window.location.pathname是一天结束时的字符串,因此通常的字符串方法适用.