Hulk1991
Hulk1991

Reputation: 3153

Replace the parameter in URL & refresh the page

My Default URL will be like

http://localhost:4444/index.html?file=sample

And I have a drop down list with various filenames, I want to replace the parameter sample by clicking drop down list.
For each and every change the URL should be altered with existing parameter.

I Tried with following,

location.href = location.href + "filename" ;

But it won't replace the filename.

Upvotes: 17

Views: 19458

Answers (4)

Welcome to 2018, you can now mostly use URLSearchParams to handle the 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 the parameter to the query string as needed.

Upvotes: 24

Weston Ganger
Weston Ganger

Reputation: 6712

I adapted @matewka answer to be more robust by also working when there are no existing params in 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;
}

Upvotes: 0

Dziad Borowy
Dziad Borowy

Reputation: 12579

One way is:

location.href = location.origin + location.pathname + '?file=filename';

But this would only work when you have one parameter after the ?. If you have more - you'd need to parse them and re-apply.

Upvotes: 10

matewka
matewka

Reputation: 10148

You can try this:

location.search = location.search.replace(/file=[^&$]*/i, 'file=filename');

location.search property holds only the query part of the URL so you don't have to worry that any other parts of the url (e.g. domain or hash) will be modified.
Also, the regex will replace only the file parameter. It is useful when you'll have some other parameters in query.

Upvotes: 15

Related Questions