3

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.

Shnick
  • 1,199
  • 1
  • 13
  • 32

3 Answers3

3

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.

Ian Mackinnon
  • 13,381
  • 13
  • 51
  • 67
2

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

CodeIt
  • 3,492
  • 3
  • 26
  • 37
1

Apply this script into your a tag.

<a href="javascript:document.location.href=document.location.href.split('?')[0];">Home</a>
CodeIt
  • 3,492
  • 3
  • 26
  • 37
Chaska
  • 3,165
  • 1
  • 11
  • 17