7

I've tried searching for this for 30 minutes, so I apologize if it's been asked already.

I have some Ajax which returns a set of results and when one is clicked it simply reloads the URL with the appended data to the URL for PHP to GET on the next page. The problem is, if the user clicked to some built in anchoring (which I cannot remove), the URL will be something.com#location1 so appending ?action=next will turn it into something.com#location1?action=next which the browser interprets as a long anchor, rather than a new URL to actually direct to.

If the user never clicks the anchor portion this redirect works smoothly using window.location=document.url+"?action=next"

Is there a way to remove the anchor (including the hash tag) from the existing page's URL?

SOLVED

Using Michael W's answer I was able to solve it. I simply replaced this line:

window.location=document.url+"?action=next"

With this:

window.location=document.location.href.match(/(^[^#]*)/)[0]+"?action=next"

Thanks for the help!

2
  • None of these results help you out? Commented Mar 4, 2013 at 2:20
  • I went with Michael W's solution (with a minor modification), marked as such and edited the original question to include the solution for future readers. Commented Mar 4, 2013 at 5:19

4 Answers 4

14

This seems slightly simpler:

document.URL.replace(/#.*$/, "")
Sign up to request clarification or add additional context in comments.

Comments

6

You could match for the pre-hashtag portion of the location:

document.location.href.match(/(^[^#]*)/)

1 Comment

For those reading: this returns an Array. Specifying the first element worked for me: window.location=document.location.href.match(/(^[^#]*)/)[0] I aborted using document.url entirely.
2

The location object can be accessed by independent components and you can use those to reconstruct the URL with as many or as few pieces as you like.

The official documentation is offline at this time but this site seems to have it.

Should those be internal links you are generating, you will only need to generate a relative url and maybe even just location.pathname would suffice.

Note that you tagged your question as Javascript but since you are coding in PHP, I suspect what you need is to generate those links on the PHP side.

2 Comments

location.pathname indeed works for me. But what is its difference between window.location.pathname?
@JAT86 - Those are identical in that they reference the same object. It is just accessible two ways.
1

I'm using:

document.location.href.split('#')[0];

It finds the first hash and ignore the rest of the path. If there is no hash, no problem. In this case it will take the entire path.

1 Comment

should be considered best method imo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.