Remove Anchors from a Url in Javascript
Posted on August 8th, 2008 by Jelani Harris
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://www.jelaniharris.com/blog/I-love-apple-pies#comments
To look like:
http://www.jelaniharris.com/blog/I-love-apple-pies
Here’s the ideal way to do this with Javascript:
1 2 3 4 5 6 7 | //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); } |
It doesn’t get any easier than that. What this code does is that it grabs the URL from the current window, and then finds the index into the string where the ‘#’ is. Then if it exists, it truncates the string up to the ‘#’.
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!
I’ve never used greasemonkey, but if it’s javascript then you should be able to use this code somehow.
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.
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
@Jessica
Hello there. I’d like to help, but I’m not sure what your problem is. Could you be more descriptive?