问题
I need to change the country code in the URL when I select the country from the dropdown.
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.
回答1:
you can leave out the domain and do this for all country codes.
window.location.href = "/" + formCountryCode
as the domain remains unchanged.
if there is a pathname, then you can do
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 + "/");
来源:https://stackoverflow.com/questions/65433529/changing-country-code-subdirectory-from-url