Javascript 在有效文件名(如 PHP PATH_INFO)之后获取路径



假设我有页面"example.com/page.php",您可以通过导航到"example.com/page.php/some/other/content"来更改内容。

在PHP中,我会使用$_SERVER["PATH_INFO"]变量来获取URL的"/some/other/content"部分。

我现在想构建一个页面,其中页面只加载一次,其余的由 Javascript 完成。

如何使用javascript从URL中获取"/some/other/content/"部分? 我知道我可以使用一些带有已知文件扩展名"php"的字符串操作。但我想知道是否有一些内置功能始终能够使用任何文件扩展名执行此操作。

我找不到任何关于这个的东西,因为我总是被定向到有关PHP函数pathinfo((的帖子。

提前谢谢你!

这是如何获取 url 的那部分的最基本示例,您可以在线找到更多示例。

var url = "https://example.com/page.php/some/other/content";
console.log(url.split('php')[1]);

由于似乎没有内置解决方案,我想出了这个函数。我发布它以防其他人需要它:

function getPathPosition(url){
//path/without/host/page.html/some/other/content
let dirs = url.split("/");
let fileFound = false;
dirs = dirs.filter((item)=>{
if(!fileFound && item.includes(".")){
fileFound = true;
return false;
}
else{
return fileFound;
}
});
return "/" + dirs.join("/");
}

这在以下条件下有效:

  • 该文件中有一个点(因此它可能也有扩展名(。
  • 主机已被移除
  • URL 的查询和哈希部分已被删除

相关内容

最新更新