簡體   English   中英

如何在 JavaScript 中獲取當前 URL 的目錄部分?

[英]How to get the directory part of current URL in JavaScript?

我正在嘗試在網頁頂部添加一個“返回目錄”按鈕,該按鈕會將用戶重定向到相同的 URL,但其中沒有文件名。

例如,在查看 URL 時單擊該按鈕

http://example.com/somedir/button.html

會將您重定向到

http://example.com/somedir/

所以我創建了以下代碼:

<html>
<body>

<input type="button"
value="back to dir"
onclick="top.location=document.URL.replace(/[^\\]*$/, '')">

</body>
</html>

但我缺少正確的代碼,這會從document.URL的當前 URL 中刪除文件名

請問這里有人有什么好主意嗎?

這是 JSFiddle 鏈接: http : //jsfiddle.net/afarber/PERBY/

我不想這一次不使用 jQuery。

試試這個document.URL.substr(0,document.URL.lastIndexOf('/'))

它肯定會起作用!

這種單線也有效:

document.URL.split('/').slice(0, -1).join('/')
/* to avoid query parameters, use pathname instead of href */
var l = document.location.pathname.split('/');
l.pop();
console.log(document.location.origin + l.join('/'));

以下獲取目錄,包括最后一個字符是斜杠的情況。

document.URL.replace(/\/[^/]+\/?$/, '');

這有效地說明了以下內容(假設可以按此順序找到它們)

  1. \\/ : 找到一個“/”
  2. [^/]+ : 查找后一個或多個不是“/”的字符
  3. \\/? : 在這些字符后找到一個可選的“/”
  4. $ : 查找字符串的結尾

然后通過''刪除這些,所以我們只剩下目錄。

同樣,這種假設一個斜線現在標志着一個目錄,這是不是只是其中唯一的斜杠是內URL http://

 console.log(new URL(document.URL));

你會得到這樣的所有對象:

{
  href:"https://yy.xx.id/index.php/5351/user/private/images%20%282%29.jpeg?forcedownload=1",

  origin:"https://smi.kerjaindonesia.id", 
  protocol: "https:", 
  username: "", 
  password: "", 
  pathname: "index.php/5351/user/private/images%20%282%29.jpeg"  ,
  port: "" ,
  protocol: "https:",
  search: "?forcedownload=1"
}

嘗試以下操作,其中考慮了 URL 何時以斜杠結尾以及何時不以斜杠結尾:

var currUrl = document.URL,
    newUrl;
if (currUrl.charAt(currUrl.length - 1) === '/') {
    newUrl = currUrl.slice(0, currUrl.lastIndexOf('/'));
    newUrl = newUrl.slice(0, newUrl.lastIndexOf('/')) + '/';
} else {
    newUrl = currUrl.slice(0, currUrl.lastIndexOf('/')) + '/';
}
console.log(newUrl);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM