javascript - 从 URL 更改国家代码子目录
问题描述
当我从下拉列表中选择国家时,我需要更改 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 + "/");
推荐阅读
- google-apps-script - Google Script 有两个用于编辑时的触发器。我可以删除“简单”的吗?
- oracle - 为时间戳字段插入 SYSTIMESTAMP
- flutter - 如何显示从时间戳经过的时间?
- selenium - 使用 Robot Framework 处理随机按钮
- java - 创建基于位置的应用程序而不保存坐标
- javascript - 每个模块只有一个默认导出允许使用 Navbar 在 React Native 上出错
- angular - 添加确认对话框作为按钮的添加属性指令
- ruby-on-rails - rake db:migrate:不兼容的库版本 postgres
- laravel - 如何使用 Vue 和 Laravel 避免警告“直接改变道具”
- excel - 如果其中一个工作簿具有自动保存功能,如何分离 Excel 实例?