removing the # from window.location.hash
Asked Answered
I

4

35

I have this simple script:

$(document).ready(function(){

var $yoyo = window.location.hash;

alert($yoyo);

});

But I need to get rid of the # symbol as I'll be using the variable to locate div ids. I've tried using .remove('#') but that doesn't seem to be working.

Many thanks in advance!

Inter answered 30/7, 2010 at 23:14 Comment(1)
C
93
var $yoyo = window.location.hash.substring(1);

This simply means we're taking a substring consisting of character 1 (0-indexed, so second) onwards. See the substring docs.

Catarina answered 30/7, 2010 at 23:18 Comment(2)
This works as long as the string actually starts with "#", but it could be argued that this is more robust and easier to read: window.location.hash.replace(/^#/, "").Ruberta
@ChristianDavén window.location.hash will always have a hash in front or be empty, and ''.substring(1) === '', so I think that solution is pretty robust. I do think yours is more readable though. (Also see lea.verou.me/2011/05/get-your-hash-the-bulletproof-way)Hospitaler
B
15
var $yoyo = window.location.hash.replace("#", "");

.remove() is a jQuery dom manipulation function. .replace() is a native javascript function that replaces a string with another string inside of a string. From W3Schools:

<script type="text/javascript">

var str="Visit Microsoft!";
document.write(str.replace("Microsoft", "W3Schools"));

</script>
Barris answered 30/7, 2010 at 23:18 Comment(2)
Of course since this is Stack Overflow, it's a jQuery DOM manipulation function. But in fact it could be anything. -_-Acerbate
@Will, the post was tagged with jQuery. It couldn't be just anything ;)Barris
K
3
$yoyo.substr(1)
Killian answered 30/7, 2010 at 23:18 Comment(0)
P
2

For those who may not have read the lea verou blog shared by Steve Harrison, a version with 4 less bytes and using newer JS definitions would be:

let $yoyo = window.location.hash.slice(1)

Slice is an array method that when given one index returns the values from the starting index to the last index. Since strings in Javascript are considered an array of characters and the location hash will always have a starting # or be an empty string, this works.

http://lea.verou.me/2011/05/get-your-hash-the-bulletproof-way/

Phalansterian answered 6/8, 2021 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.