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!
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!)
As you suspected, there's also a shift()
function on the Array
prototype (MDN).
Strings are not Array
s, 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("");
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With