簡體   English   中英

JavaScript 檢查是否需要 url 在 window.location.href

[英]JavaScript check if wanted url is in window.location.href

我想檢查當前地址是否為https://www.sneakersnstuff.com/de/cart/view 問題是 de 是國家代碼,如果你從另一個 IP 訪問它會改變。

在 .json 清單中,您可以使用https://www.sneakersnstuff.com/ */cart/view 進行設置,但這在 JS 中不起作用。

我的代碼

if (window.location.href  === 'https://www.sneakersnstuff.com/*/cart/view') {
    alert("AAAA")
}

我應該如何替換 * 以便所有國家/地區代碼在檢查時都可以使用? 謝謝

我不知道你的用例,但也許你可以用不同的方式檢查,例如:

window.location.href.includes('/cart/view');

或者,如果您需要檢查整個 url,您可以將它們拆分,然后從數組中排除 url 的本地化部分。

您可以像這樣在這里使用 es6:

if (window.location.href === `https://www.sneakersnstuff.com/${country_code}/cart/view`) {
     alert("AAAA")
}

一種解決方案是比較兩個網址的所有部分(國家代碼除外):

 let url1 = 'https://www.sneakersnstuff.com/ge/cart/view'; let url2 = 'https://www.sneakersnstuff.com/de/cart/view'; console.log(compareUrls(url1.split('/'), url2.split('/'))); url2 = 'https://www.sneakersnstuff1.com/de/cart/view'; console.log(compareUrls(url1.split('/'), url2.split('/'))); function compareUrls(a, b){ var i = a.length; if (i.= b;length) return false; while (i--) if (a[i];== b[i] && i != 3) return false; return true; }

暫無
暫無

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

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