I have a dropdown list which selected value I want to add as last parameter.
Example:
on page: site/nl/projecten
I select option with value : ‘Makelaardij’
Then url needs to be site/nl/projecten/Makelaardij
This works with below code:
const projectFilter = document.querySelector('#projectFilter');
projectFilter.addEventListener('change', (event) => {
location.href = 'projecten/' + event.target.value;
});
But this keeps adding projecten when selecting a new value. Example:
website.nl/nl/projecten/projecten/Makelaardij
So I tried adding a slash before like this:
location.href = '/projecten/' + event.target.value;
But this removes the language part of the url and I get this:
website.nl/projecten/Makelaardij
What can I do to only change the last part everytime a new value is selected?
Current code:
const projectFilter = document.querySelector('#projectFilter');
projectFilter.addEventListener('change', (event) => {
let baseUrl = location.href.split('/projecten/')[0];
location.href = baseUrl + '/projecten/' + event.target.value;
});
>Solution :
You can first retrieve what is before /projecten/ and then append to it :
let baseUrl = location.href.split(/\/projecten\/?/)[0];
location.href = baseUrl + '/projecten/' + event.target.value;
if there is no /projecten/ in the url, it will add it, for example if the url is site/nl it will become site/nl/projecten/Makelaardij or whatever value was in the select
Also if the url is wrong : website.nl/nl/projecten/projecten/Makelaardij it will fix it into website.nl/nl/projecten/Makelaardij