如果我有一个像这样的网址:
http://localhost:53830/Organisations/1216/View
我想以小写格式提醒 url 路径的第一部分,例如“组织”
到目前为止我已经:
var first = $(location).attr('pathname');
first.indexOf(1);
first.replace('/', '');
first.toLowerCase();
alert(first);
但它没有按预期工作。有人可以帮忙吗?谢谢
最佳答案
这永远不会抛出错误,因为路径名总是以 /
开头,因此分割后结果数组的最小长度将为 2:
const firstPath = location.pathname.split('/')[1];
如果我们位于域根目录,返回的值将是一个空字符串''
const path = location.pathname.split('/');
path = [
'',
'questions',
'8082239',
'get-the-first-part-of-a-url-path',
'8082346'
];
关于javascript - 获取 url 路径的第一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082239/