【发布时间】:2019-10-01 09:51:24
【问题描述】:
我有一个电子商务 Shopify URL,我需要检查特定字符串以确定是否更改货币。 当用户登陆网站时,URL 是例如https://www.myshop.com.
在导航栏中,有一些按钮允许用户从默认的美元货币更改为当地货币。 这是 Shopify 的原生功能,需要您在 URL 中添加 ?currency=GBP(例如英镑)。
我检查字符串 ?currency= 是否存在,如果存在则表示用户已经选择了一种货币,但想再次更改它。所以我从 ? 的开头去掉 13 个字符,然后用新的货币字符串替换它。
问题是,如果有人通过广告登陆网站,则 URL 可能看起来像 https://www.myshop.com?HkuhJKh6876MJ。
那么我必须将货币 URL 更改为 & 而不是 ? 我可以遍历字符串并检查超过 1 个 ? 然后更改 URL,但它似乎冗长。有没有更好的方法来做到这一点?
以下是我当前的代码,用于检查 ?currency= 子字符串,如果存在,则将其删除并替换为新货币。
<input type="button" value="Show USD" onclick="showUSD()">
<input type="button" value="Show GBP" onclick="showAUD()">
<script>
function showUSD() {
var changeToCurrency = "USD"; // Set selected currency
checkForSubstring(changeToCurrency); // Check for '?currency=' substring
}
function showGBP() {
var changeToCurrency = "GBP";
checkForSubstring(changeToCurrency);
}
// Check for substring
function checkForSubstring (newCurrency) {
var urlString = window.location.href + "";
var currencySubstring = "?currency=";
if ((urlString.includes(currencySubstring))) {
sliceURL(urlString, currencySubstring, newCurrency);
}
else {
alert("Doesnt contain substring. \nLoading new URL.");
window.location.replace(urlString + currencySubstring + newCurrency);
}
}
// Slice URL
function sliceURL (originalURL, stringToSlice, currency) {
var n = originalURL.indexOf(stringToSlice); // Get position of substring
// Slice substring from URL
var S = originalURL + "";
var bindex = n;
var eindex = n + 13;
S = S.substr(0, bindex) + S.substr(eindex);
// Reload new URL
reloadURL(S, stringToSlice, currency);
}
// Reload URL
function reloadURL(baseURL, stc, currency) {
window.location.replace(baseURL + stc + currency);
}
</script>
【问题讨论】:
-
不确定我的问题是否正确。你不能只搜索“currency=”吗?
-
使用库解析queryString,如npmjs.com/package/query-string
-
这可以通过 cookie 更好地完成。
标签: javascript url shopify currency