The Original Jelani Harris The one and only


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:

To look like:

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.

Filed under: Uncategorized 8 Comments