我正在尝试从字符串中获取基本 url(因此没有 window.location)。
- 需要去掉尾部的斜线
- 它需要是正则表达式(没有新的 URL)
- 它需要与查询参数和 anchor 链接一起工作
换句话说,以下所有内容都应返回 https://apple.com
或 https://www.apple.com
作为最后一个。
https://apple.com?query=true&slash=false
https://apple.com#anchor=true&slash=false
http://www.apple.com/#anchor=true&slash=true&whatever=foo
这些只是示例,url 可以有不同的子域,例如 https://shop.apple.co.uk/?query=foo
应该返回 https://shop.apple。 co.uk
- 它可以是任何 url,例如:https://foo.bar
我越接近:
const baseUrl = url.replace(/^((\w+:)?\/\/[^\/]+\/?).*$/,'$1').replace(/\/$/, ""); // Base Path & Trailing slash
但这不适用于 anchor 链接和查询,这些链接和查询在 url 之后开始,之前没有 /
知道如何让它适用于所有情况吗?
最佳答案
您可以将 #
和 ?
添加到您的 negated character class .您不需要 .*
因为它将匹配到字符串的末尾。
对于您的示例数据,您可以 match :
^https?:\/\/[^#?\/]+
strings = [
"https://apple.com?query=true&slash=false",
"https://apple.com#anchor=true&slash=false",
"http://www.apple.com/#anchor=true&slash=true&whatever=foo",
"https://foo.bar/?q=true"
];
strings.forEach(s => {
console.log(s.match(/^https?:\/\/[^#?\/]+/)[0]);
})
关于javascript - 使用 Regex 和 Javascript 从字符串中获取基本 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54118061/