Javascript 获取 url 路径的第一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8082239/
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
Get the first part of a url path
提问by Cameron
If I have a url like:
如果我有一个像这样的网址:
http://localhost:53830/Organisations/1216/View
http://localhost:53830/Organisations/1216/View
I want to alert the first part of the url path in lowercase format e.g. 'organisations'
我想以小写格式提醒 url 路径的第一部分,例如“组织”
So far I have:
到目前为止,我有:
var first = $(location).attr('pathname');
first.indexOf(1);
first.replace('/', '');
first.toLowerCase();
alert(first);
but it's not working as intended. Can anyone help? Thanks
但它没有按预期工作。任何人都可以帮忙吗?谢谢
采纳答案by Dogbert
var first = $(location).attr('pathname');
first.indexOf(1);
first.toLowerCase();
first = first.split("/")[1];
alert(first);
回答by Samuel Liew
This will never throw an error because pathname always starts with a /
, so the minimum length of the resulting array will be 2 after splitting:
这永远不会抛出错误,因为路径名总是以 a 开头/
,因此拆分后结果数组的最小长度将为 2:
const firstPath = window.location.pathname.split('/')[1];
If we are at the domain root, the returned value will be an empty string ""
.
如果我们在域根,返回的值将是一个空字符串""
。
回答by Antagonist
try to use first.split('/')
so you will end up with an array of strings like
尝试使用first.split('/')
这样你最终会得到一个字符串数组,比如
['http:' ,'', 'localhost:53830' , 'Organisations' , '1216' , 'View' ]
then find the one the is right after localhost:53830
然后找到 localhost:53830 之后的那个
回答by DAVID AJAYI
You may need to add window
keyword so you don't get error:Cannot read property 'pathname' of undefined
您可能需要添加window
关键字,以免得到error:Cannot read property 'pathname' of undefined
var location = window.location.pathname.split('/')[1]