从 URL 更改国家代码子目录

Changing country code subdirectory from URL

当我从下拉列表中 select 国家时,我需要更改 URL 中的国家代码。

目前我在下拉列表中只有3个国家,但是当我从SG(testing.com/sg/features)切换到IE时,结果URL变成了(testing.com/ie/sg/features) .当我从 IE(testing.com/ie/features) 切换到 SG(testing.com/sg/features) 时它工作正常。

<form name="form1">
    <select class="region regionTopBar" onchange="formChanged(this);" name="country" size="1" style="font-family: inherit; padding: 5px; border:0px; outline:0px;">
        <option value="/">International</option>
        <option value="sg/">Singapore</option>
        <option value="ie/">Ireland</option>
    </select>
</form>

<script>
function formChanged(form) {
  var formCountryCode = form.options[form.selectedIndex].value;
  var formCountryName = form.options[form.selectedIndex].text;
        if (formCountryCode !== null) {
          if (localStorage) {
            localStorage.country = formCountryCode ;
            localStorage.currentSite = formCountryName ;
          }
        if(formCountryCode == "sg/"){
            var url = window.location.href.replace("testing.com/", "testing.com/sg/");
            location = url;
        }
        else if(formCountryCode == "ie/"){
            var url = window.location.href.replace("testing.com/", "testing.com/ie/");
            location = url;
        }

//remove country code from URL when International is selected
          else {
                var thisLocation = window.location.href;
        
                var splitLoc = thisLocation.split('/');
                var newLocation = "";

                for (let i = 0; i < splitLoc.length; i++){
                    if (splitLoc[i] !== "sg" && splitLoc[i] !== "ie")
                        newLocation += splitLoc[i] + '/';
                }

                newLocation = newLocation.substring(0, newLocation.length - 1);
                location = newLocation ;
          }
        }
    }
</script>

像这样添加 if else 可以解决问题,但随着国家数量的增加,它会变得一团糟。

else if(formCountryCode == "ie/"  && window.location.href.indexOf("sg/") < 1){
    var url = window.location.href.replace("testing.com/", "testing.com/ie/");
    location = url;
}
else if(formCountryCode == "ie/" && window.location.href.indexOf("sg/") > 0){
    var url = window.location.href.replace("testing.com/sg/", "testing.com/ie/");
    location = url;
}

所以我正在寻找一种动态的方法来实现这一点。

您可以省略域并对所有国家/地区代码执行此操作。

window.location.href = "/" + formCountryCode

因为域保持不变。

如果有路径名,那么你可以

window.location.href = window.location.pathname.replace(/\/.+?\//, "/" + formCountryCode + "/")

如果路径名是 / 那么我们可以这样做

const path = window.location.pathname;

window.location.href = path === "/" ?
    "/" + formCountryCode :
    path.replace(/\/.+?\//, "/" + formCountryCode + "/");