Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change only last parameter of url using javascript instead of appending to it

I have a dropdown list which selected value I want to add as last parameter.

Example:

on page: site/nl/projecten

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading