JavaScript: 如何从 URL 路径中删除最后一个部分
使用 JavaScript 从 URL 路径中移除最后一个部分可以使用以下方法:
var pathname = window.location.pathname;
var lastIndex = pathname.lastIndexOf('/');
var newPathname = pathname.substring(0, lastIndex);
console.log(newPathname);
此代码将打印去除最后一个路径部分后的新路径。
解释:
window.location.pathname获取当前 URL 的路径部分。lastIndexOf('/')查找最后一个/字符的位置。substring(0, lastIndex)从路径的开始位置(索引 0)到最后一个/的位置截取字符串。
例如,如果 URL 为 http://example.com/folder1/folder2/file.html,则 newPathname 将为 http://example.com/folder1/folder2。
原文地址: https://www.cveoy.top/t/topic/qeXJ 著作权归作者所有。请勿转载和采集!