Javascript 从URL更改国家/地区代码子目录

Javascript 从URL更改国家/地区代码子目录,javascript,substring,href,subdirectory,country-codes,Javascript,Substring,Href,Subdirectory,Country Codes,当我从下拉列表中选择国家时,我需要更改URL中的国家代码 目前,下拉列表中只有3个国家/地区,但当我从SG(testing.com/SG/features)切换到IE时,生成的URL变成(testing.com/IE/SG/features)。当我从IE(testing.com/IE/features)切换到SG(testing.com/SG/features)时,它工作得很好 国际的 新加坡 爱尔兰 功能表单已更改(表单){ var formCountryCode=form.options[

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

目前,下拉列表中只有3个国家/地区,但当我从SG(testing.com/SG/features)切换到IE时,生成的URL变成(testing.com/IE/SG/features)。当我从IE(testing.com/IE/features)切换到SG(testing.com/SG/features)时,它工作得很好


国际的
新加坡
爱尔兰
功能表单已更改(表单){
var formCountryCode=form.options[form.selectedIndex].value;
var formCountryName=form.options[form.selectedIndex].text;
如果(formCountryCode!==null){
if(本地存储){
localStorage.country=formCountryCode;
localStorage.currentSite=formCountryName;
}
如果(formCountryCode==“sg/”){
var url=window.location.href.replace(“testing.com/”,“testing.com/sg/”;
位置=url;
}
如果(formCountryCode==“ie/”),则为else{
var url=window.location.href.replace(“testing.com/”,“testing.com/ie/”;
位置=url;
}
//选择“国际”时从URL中删除国家代码
否则{
var thisLocation=window.location.href;
var splitLoc=thisLocation.split('/');
var newLocation=“”;
for(设i=0;i
如果再加上其他类似的方法可以解决问题,但随着国家数量的增加,情况将变得一团糟

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;
}
else if(formCountryCode==“ie/”&&window.location.href.indexOf(“sg/”)<1){
var url=window.location.href.replace(“testing.com/”,“testing.com/ie/”;
位置=url;
}
else if(formCountryCode==“ie/”&&window.location.href.indexOf(“sg/”)>0){
var url=window.location.href.replace(“testing.com/sg/”,“testing.com/ie/”;
位置=url;
}

因此,我正在寻找一种动态方法来实现这一点。

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

window.location.href=“/”+formCountryCode
因为域名保持不变

如果有路径名,则可以执行以下操作

window.location.href=window.location.pathname.replace(/\/.+?\/,“/”+formCountryCode+“/”)
如果路径名为/则我们可以执行此操作

const path=window.location.pathname;
window.location.href=path==“/”?
“/”+formCountryCode:
路径。替换(/\/.+?\//,“/”+formCountryCode+“/”);

testing.com是您的主机名吗?不是,但它只是一个域的示例。但这只会进入主页(testing.com/sg/),而不是(testing.com/sg/features)。更新了我的答案以处理您的使用案例!我不知道这种方法,但效果很好。谢谢你的回答,伙计。祝你愉快:)哦,有一只虫子。当您在testing.com上并且想要访问testing.com/sg/时,它不起作用。你如何处理这个问题呢?我在回答中添加了更多的代码
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;
}