[英]Way to extract a portion of a path from a URL using JavaScript?
有什么方法可以使用 JavaScript 从 URL 中提取完整路径的一部分?
示例:我有 URL http://www.somedomain.com/account/6099bb4e2eb24bab85e8b76851a14260/search?filter=a#top
但我只想得到这部分6099bb4e2eb24bab85e8b76851a14260
这是一个随机 id 几个例子,如:
6099bb4e2eb24bab85e8b76851a14260,
93b04efd1a734407b28f95d9c5278c0f,
94c9483fdb3747b38e4836fe9294cbfe,
93b04efd1a734407b28f95d9c5278c0f
请帮帮我...它让我发疯。 学习....
你可以像这样去做,
const url=new URL('http://www.somedomain.com/account/6099bb4e2eb24bab85e8b76851a14260/search?filter=a#top');
/*
url.pathname="/account/6099bb4e2eb24bab85e8b76851a14260/search"
url.pathname.split('/')=["","account","6099bb4e2eb24bab85e8b76851a14260","search"]
*/
const accountId=url.pathname.split('/')[2];
console.log(accountId);
有关如何在 JS 中使用URL
对象的更多信息,请参阅此内容, https://developer.mozilla.org/en-US/docs/Web/API/URL
这应该会得到你想要的结果。
function myFunction() {
var url = "http://www.somedomain.com/account/6099bb4e2eb24bab85e8b76851a14260/search?filter=a#top";
var result = str.split('/')[4];
console.log(result);
}
这是分割url字符串并选择所需值的位置的简单示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.