Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the parameter in URL & refresh the page

Tags:

javascript

url

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.

like image 854
Hulk1991 Avatar asked Oct 23 '13 10:10

Hulk1991


People also ask

What is a parameter in a URL?

URL parameter is a way to pass information about a click through its URL. You can insert URL parameters into your URLs so that your URLs track information about a click. URL parameters are made of a key and a value separated by an equals sign (=) and joined by an ampersand (&).

How can I remove URL parameters without refreshing page?

Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.

How can I add or update a query string parameter?

You can use the browser's native URL API to do this in a fairly simple way, where key and value are your parameter name and parameter value respectively. const url = new URL(location. href); url. searchParams.


1 Answers

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.

like image 187
matewka Avatar answered Oct 13 '22 10:10

matewka