My default url will look like
http://localhost:4444/index.html?file=sample
And I have a drop-down list with different file names, I want to replace the parameter sampleby clicking the drop-down list.For each change, the URL must be changed using an existing parameter.
sample
I tried with the following,
location.href = location.href + "filename" ;
But it will not replace the file name.
One of the methods:
location.href = location.origin + location.pathname + '?file=filename';
But this will only work when you have one parameter after ?. If you have more, you need to analyze them and resubmit the application.
?
You can try the following:
location.search = location.search.replace(/file=[^&$]*/i, 'file=filename');
location.search URL-, , URL- (, ) ., file. , .
location.search
file
Welcome to 2018, now you can mainly use URLSearchParams to handle parsing and replacing you get
var params = new URLSearchParams(location.search); params.set('file', 'sample'); window.location.search = params.toString();
URLSearchParams will replace or add a parameter to the query string as necessary.
I adapted @matewka's answer to be more reliable, also working when there are no existing parameters in window.location.search
window.location.search
var filename = 'myFilename.csv'; var paramName = 'file'; var newParam = paramName + '=' + filename; if(window.location.search){ var regex = new RegExp(paramName + '=[^&$]*', 'i'); window.location.search = window.location.search.replace(regex, newParam); }else{ window.location.search = newParam; }