gpt4 book ai didi

Javascript Regex 去掉 URL 的最后一部分 - 在最后一个斜杠之后

转载 作者:搜寻专家 更新时间:2023-11-01 05:07:31 25 4
gpt4 key购买 nike

本质上,我需要一个 JS 正则表达式来弹出 URL 的最后一部分。它的问题是,如果它只是域名,比如 http://google.com ,我不想改变任何东西。

下面是例子。非常感谢任何帮助。

http://google.com -> http://google.com
http://google.com/ -> http://google.com
http://google.com/a -> http://google.com
http://google.com/a/ -> http://google.com/a
http://domain.com/subdir/ -> http://domain.com/subdir
http://domain.com/subfile.extension -> http://domain.com
http://domain.com/subfilewithnoextension -> http://domain.com

最佳答案

我发现不使用正则表达式这更简单。

var removeLastPart = function(url) {
var lastSlashIndex = url.lastIndexOf("/");
if (lastSlashIndex > url.indexOf("/") + 1) { // if not in http://
return url.substr(0, lastSlashIndex); // cut it off
} else {
return url;
}
}

示例结果:

removeLastPart("http://google.com/")        == "http://google.com"
removeLastPart("http://google.com") == "http://google.com"
removeLastPart("http://google.com/foo") == "http://google.com"
removeLastPart("http://google.com/foo/") == "http://google.com/foo"
removeLastPart("http://google.com/foo/bar") == "http://google.com/foo"

关于Javascript Regex 去掉 URL 的最后一部分 - 在最后一个斜杠之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6319847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com