Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift js string one character

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!

like image 666
Julian H. Lam Avatar asked Jul 08 '10 03:07

Julian H. Lam


3 Answers

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!)

like image 62
Dean Harding Avatar answered Oct 31 '22 17:10

Dean Harding


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("");
like image 44
Ben Avatar answered Oct 31 '22 18:10

Ben


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();
like image 34
GMeister Avatar answered Oct 31 '22 18:10

GMeister