簡體   English   中英

如何從 window.location.pathname 中刪除尾部斜杠

[英]How to remove trailing slash from window.location.pathname

我有以下代碼允許我在我的網站的桌面和移動版本之間切換,

<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera 
Mini/i.test(navigator.userAgent) ) {
window.location = "http://m.mysite.co.uk";
}
</script>

我最近意識到所做的一切就是將每個人發送到該網站的主頁。 我仔細研究了一下,認為我可以通過修改上述內容將特定頁面重定向到移動版本,

<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 window.location = "http://m.mysite.co.uk" +  window.location.pathname;
}
</script>

唯一的問題是 URL 路徑末尾的斜杠導致無法識別 URL。

有沒有辦法在 Javascript 中刪除尾部斜杠?

該站點位於舊的 Windows 2003 服務器上,因此它是 IIS6,以防有人建議使用 URL 重寫模塊。

感謝您提供的任何建議。

要解決多個尾部斜杠的問題,您可以使用此正則表達式刪除尾部斜杠,然后使用結果字符串而不是window.location.pathname

const pathnameWithoutTrailingSlashes = window.location.pathname.replace(/\/+$/, '');

刪除/之前和之后,使用這個(雖然不漂亮)

let path = window.location.pathname.replace(/\/+$/, '');
path = path[0] == '/' ? path.substr(1) : path;

只需使用一個簡單的測試並刪除尾部斜杠:

var path = window.location.pathname;
path = path[0] == '/' ? path.substr(1) : path;

不是 OP 要求的確切內容,但根據您的用例,這里有一些正則表達式變體。

let path = yourString.replace(/\//g,''); // Remove all slashes from string

let path = yourString.replace(/\//,''); // Remove first slash from string

let path = yourString.replace(/\/+$/, ''); // Remove last slash from string
window.location.pathname.slice(1)

暫無
暫無

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

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