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!

circey
  • 2,032
  • 6
  • 35
  • 51

4 Answers4

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.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 9
    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(/^#/, "")`. – Christian Davén May 02 '16 at 09:14
  • @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 http://lea.verou.me/2011/05/get-your-hash-the-bulletproof-way/) – Steve Harrison Mar 01 '17 at 01:05
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>
Mike Sherov
  • 13,277
  • 8
  • 41
  • 62
3
$yoyo.substr(1)
Anurag
  • 140,337
  • 36
  • 221
  • 257
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/

Ife Lawal
  • 69
  • 1
  • 4