从URL更改国家代码子目录 [英] Changing country code subdirectory from URL
问题描述
从下拉列表中选择国家/地区后,我需要更改网址中的国家/地区代码.
I need to change the country code in the URL when I select the country from the dropdown.
当前,我在下拉菜单中只有3个国家/地区,但是当我从SG(testing.com/sg/features)切换到IE时,结果URL变为(testing.com/ie/sg/features).当我从IE(testing.com/ie/features)切换到SG(testing.com/sg/features)时,效果很好.
Currently I only have 3 countries in the dropdown, but when I switch from SG (testing.com/sg/features) to IE, the resulting URL becomes (testing.com/ie/sg/features). It works fine when I switch from IE(testing.com/ie/features) to SG(testing.com/sg/features) tho.
<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>
添加其他类似方法可以解决此问题,但是随着国家/地区数量的增加,情况将会变得一团糟.
Adding if else like this can fix the issue but as the number of countries increase, it is going to be a mess.
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;
}
所以我正在寻找一种动态的方法来实现这一目标.
So I am looking for a dynamic way to achieve this.
推荐答案
您可以忽略域,并针对所有国家/地区代码执行此操作.
you can leave out the domain and do this for all country codes.
window.location.href = "/" + formCountryCode
因为域保持不变.
如果有路径名,则可以
window.location.href = window.location.pathname.replace(/\/.+?\//, "/" + formCountryCode + "/")
如果路径名是/,那么我们可以这样做
if the pathname is / then we can do this
const path = window.location.pathname;
window.location.href = path === "/" ?
"/" + formCountryCode :
path.replace(/\/.+?\//, "/" + formCountryCode + "/");
这篇关于从URL更改国家代码子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!