Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove query string from URL using href

Tags:

html

url

Currently, my page URL looks something like so:

https://example.com/eg?page=2

The URL can also sometimes look like:

https://example.com/eg/?page=2

I want to redirect the user to the same page, but without the query string, so that when clicking on a link it will take you to:

https://example.com/eg

I tried using the following href in an anchor tag suggested in this question:

<a href=".">To home</a>

When clicking on the link, it removes the query string like I want when the current page URL is https://example.com/eg/?page=2. However, if the page URL is https://example.com/eg?page=2 it takes me to https://example.com.

Question: Is there some type of directory path (ie url I can use in my href) I can use such that the two above URLs will always remove the query string? I can use javascript, but if a solution without is possible that would be preferred.

Note: I cannot hard code eg into my href url as I'm developing a widget which can sit in different environments, so, eg is subject to change.

like image 655
Shnick Avatar asked Oct 16 '25 19:10

Shnick


2 Answers

A relative link beginning with ? should only modify the query string, so you could use:

<a href="?">Home</a>

Which would direct your example URLs to:

https://example.com/eg?
https://example.com/eg/?

It does include the ? in the final URL, which might not be what you want, but it is a functional option if you don't want to use Javascript.

like image 96
Ian Mackinnon Avatar answered Oct 19 '25 11:10

Ian Mackinnon


You can use,

<a href="javascript:window.location.href=window.location.href.split('?')[0];">Home</a>

You can also use document.location instead of window.location. But it is not recommended. See here

like image 35
CodeIt Avatar answered Oct 19 '25 10:10

CodeIt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!