I'm trying to get the last array item after doing a split on a string using javascript.
var str ="Watch-The-Crap-456".split('-')[this.length];
console.log(str);
// want it to console log 456, now it consoles WATCH which is in array[0]
I tried doing [this.length - 1]
to get me the last array item, but it gives me undefined, I know some of you might say create another variable to store the array, but it's interesting to see if we can keeps things shorter.
slice(-1) will return a copy of the last element of the array, but leaves the original array unmodified. To remove the last n elements from an array, use arr. splice(-n) (note the "p" in "splice"). The return value will be a new array containing the removed elements.
To get the last item without knowing beforehand how many items it contains, you can use the length property to determine it, and since the array count starts at 0, you can pick the last item by referencing the <array>. length - 1 item.
The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
How about:
"Watch-The-Crap-456".split('-').pop(); // returns 456
this
is defined in the deference (or at least does not reference the array).
A naive way would be two lines:
var str ="Watch-The-Crap-456".split('-');
console.log(str[str.length - 1]);
See it in action.
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