user3699344
user3699344

Reputation: 93

Replace a part of the URL with dropdown value - onchange

I have a language selector dropdown in my site.

On change of the language the URL redirects to the respective site

My Current URL is https://www.example.com/mem/ca/en/pages/home.aspx

On change of the language, the URL should be like

https://www.example.com/mem/ca/en/pages/home.aspx - on selecting english https://www.example.com/mem/ca/el/pages/home.aspx - on selecting Español https://www.example.com/mem/ca/py/pages/home.aspx - on selecting Pусский and so on for all the languages

<pre>
$("#dd-language").on("change", function() { 
   var countryAppend = $(this).val();
   var pathArray = window.location.pathname.split('/')[4];
   var res = pathArray.replace(pathArray,countryAppend);
   var newURL = window.location.host + "/" + pathArray;
   window.location = newURL;
});
</pre>

This adds the value at the end of the URL but I need it to replace the language code in the URL

Upvotes: 2

Views: 182

Answers (3)

mplungjan
mplungjan

Reputation: 177691

A regular expression should be useful here

$("#dd-language").on("change", function() { 
   var countryAppend = $(this).val();
   var url = location.href;
   window.location = url.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages");
});

Example

countryAppend ="xx"
console.log(
`https://www.example.com/mem/ca/en/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages"),
`https://www.example.com/mem/us/el/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages"),
`https://www.example.com/mem/mx/py/pages/home.aspx`.replace(/\/.{2}\/pages/,"/"+countryAppend+"/pages")
)

Upvotes: 0

user5845598
user5845598

Reputation:

document.querySelector('#dd-language').addEventListener('change',function(){
    let url = window.location.href.split('/');
    url[5] = this.value;
    url = url.join('/');
    window.location = url;
});

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370679

Once you have the array of the pathname split by /, overwrite the [2]nd item in the array with the new language, then join by /s again:

$("#dd-language").on("change", function() { 
   var countryAppend = $(this).val();
   var pathArray = window.location.pathname.split('/');
   pathArray[2] = countryAppend;
   var newURL = window.location.host + pathArray.join('/');
   window.location = newURL;
});

Eg, for

/mem/ca/en/pages/home.aspx

On splitting by /, the 2nd item in the array will be the ca:

const pathArr = '/mem/ca/en/pages/home.aspx'.split('/');
pathArr[2] = 'el';
console.log(pathArr.join('/'));

so reassigning that array item and then joining results in the desired output.

Upvotes: 1

Related Questions