如何解决Javascript正则表达式摆脱URL的最后部分-最后一个斜杠之后
| 本质上,我需要一个JS Regexp来弹出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
解决方法
我利用了DOM中的ѭ1。
function returnLastPathSegment(url) {
var a = document.createElement(\'a\');
a.href = url;
if ( ! a.pathname) {
return url;
}
a.pathname = a.pathname.replace(/\\/[^\\/]+$/,\'\');
return a.href;
}
jsFiddle。
, 我发现不使用正则表达式就更简单了。
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\"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。