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.
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 (&).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With