9

In PHP, it's pretty simple, I'd assume, array_shift($string)?

If not, I'm sure there's some equally simple solution :)

However, is there any way to achieve the same thing in JavaScript?

My specific example is the pulling of window.location.hash from the address bar in order to dynamically load a specific AJAX page. If the hash was "2", i.e. http://foo.bar.com#2...

var hash = window.location.hash; // hash would be "#2"

I'd ideally like to take the # off, so a simple 2 gets fed into the function.

Thanks!

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73

3 Answers3

17
hash = hash.substr(1);

This will take off the first character of hash and return everything else. This is actually similar in functionality to the PHP substr function, which is probably what you should be using to get substrings of strings in PHP rather than array_shift anyway (I didn't even know array_shift would work with strings!)

Dean Harding
  • 71,468
  • 13
  • 145
  • 180
  • Cheers to the both of you :) As far as I know, "string" isn't exactly a real type, but rather an array of characters, as we've all been taught way way (way?) back when. Theoretically, it should work, as you can point to a character in a string with $string[x]. – Julian H. Lam Jul 08 '10 at 04:36
  • 1
    I just tried it out, and `array_shift` actually *does not* work on strings in PHP, which makes sense to me. @Julian: what you say is true of strings in C and C++ but in most other languages (Java, C#, PHP, Python, etc), strings are their own data type mostly unrelated to arrays. – Dean Harding Jul 08 '10 at 04:45
  • 2
    Use `substring` instead of `substr`. The former is standardised. – James Jul 08 '10 at 07:12
5

As you suspected, there's also a shift() function on the Array prototype (MDN).

Strings are not Arrays, they are "array-like objects" so to call shift() on a String, it must be split() first:

var arr = str.split("");
var char = arr.shift();
var originalString = arr.join("");
Ben
  • 54,723
  • 49
  • 178
  • 224
  • Using the original example, you'd always get the `#` (the first character, the one that got shifted) with this approach, which doesn't seem to be the goal. – Rui Ramos Jan 16 '20 at 16:51
1

Building on Ben's point regarding conversion to an Array, given that we are assuming there is only one character as the hash, and that it is the last character, we should really just use:

var hash = window.location.split("").pop();
GMeister
  • 331
  • 2
  • 15