The Original Jelani Harris The one and only

8Aug/088

Remove Anchors from a Url in Javascript

Here is something useful that I discovered in my programming for the Apparatus Complex. I needed to strip out the anchor portion of a link and leave the rest of the url intact. For example I wanted:

http://jelaniharris.com/I-love-apple-pies#comments

To look like:

http://jelaniharris.com/I-love-apple-pies

Here's the ideal way to do this with Javascript:

	//Grab our current Url
	var url = window.location.toString();
	//Remove anchor from url using the split
	url = url.split(“#”)[0];

It doesn't get any easier than that. What this code does is grab the URL from the current window, and then splits the string where a '#' is. Whether or not if the '#' exists in the string, it'll truncates the string up to the '#' or return the whole url.

Thanks to Jonathan Rochkind in the comments for this simpler version.

Comments (8) Trackbacks (0)
  1. Hi. I was looking for a greasemonkey userscript that would enable me to automatically cull anchors from a specific site. What I would like it to do is, on that site, when I click on a link, I should get to the page I want to see and not have any anchors in the URL. Yours was the first hit on my Google search, and I tried to use your code in a bookmarklet and tried to create a GM script as well, but it did not work. Is there any way I can use the code to make it do what I want? I’d prefer an automated system of doing it, but even a bookmarklet would be very helpful.

    Thanks so much!

  2. I’ve never used greasemonkey, but if it’s javascript then you should be able to use this code somehow.

  3. Thanks for sharing and posting this bit of Javascript code! It was very helpful and worked perfectly for some similar functionality that I needed today.

  4. Hia, I have tried to use the js code as above and it doesnt seem to be working for me…. could you please help. Thanks alot.

    Jess

    test

    //Grab our current Url
    var url = window.location.toString();
    //Remove anchor from url
    var anchor_index = url.indexOf(‘#’);
    if (anchor_index != -1) {
    url = url.substring(0, anchor_index);
    }

    Test5

    This is a test

  5. @Jessica

    Hello there. I’d like to help, but I’m not sure what your problem is. Could you be more descriptive?

  6. Thanks for the snippet. I am working on disabling the current page link in my navigation menu, and this snippet along with some jQuery goodness worked perfectly for helping my compare urls whether or not they have anchors.

  7. Actually, it DOES get easier than that! Check this out:

    url = url.split(“#”)[0]

  8. Used it to remove a ?page=…

    url = url.split(“?”)[0];

    Thanks!
    L.


Leave a comment

No trackbacks yet.