【问题标题】:Iterate over a URL and add/replace string if needed如果需要,遍历 URL 并添加/替换字符串
【发布时间】: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>

【问题讨论】:

标签: javascript url shopify currency


【解决方案1】:

如果 window.location.search

中存在 currency,则以下方法将替换查询字符串中的货币值
 let updateCurrency = (CUR)=>{

    let queryString = window.location.search;
    if(queryString && queryString.length){
        queryString = queryString.slice(1);
        queryStringData = queryString.split("&");
        queryStringData.forEach((query,index)=>{
               query = query.split("=")
               if(query[0]== 'currency'){
                queryStringData.splice(index,1);
                queryStringData = queryStringData.join('&')
                            window.location.search =queryStringData +'&currency='+CUR
            }

        });

    }

    }

【讨论】:

    猜你喜欢
    • 2015-01-17
    • 2018-07-06
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多