Reputation: 2042
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!
Upvotes: 35
Views: 76533
Reputation: 69
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/
Upvotes: 2
Reputation: 13427
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>
Upvotes: 15
Reputation: 284806
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.
Upvotes: 93