0

I have a bunch of numbers coming back from an api. It looks like this

1,2,3,4,5,6

Now i'm only wanting the last digit to be displayed rather than all of them.

How would i go about doing this? I need to add .slice on the end but im not sure what to put in the ()

Thanks Sam

Sam Roberts
  • 185
  • 1
  • 12
  • 1
    Is this `array` ? If yes then `arr[arr.length-1]` – Rayon Jan 13 '16 at 11:33
  • [Selecting last element in JavaScript array](http://stackoverflow.com/questions/9050345/selecting-last-element-in-javascript-array) – Artem Jan 13 '16 at 11:33
  • If it's an array, then `arr.pop()` returns the last member. If it's a string, then `string.split(',').pop()`. – RobG Jan 13 '16 at 11:50

3 Answers3

1
var str = "1,2,3,4,5,6";    
var _lastNum = str.slice(-1*(str.length - str.lastIndexOf(",")-1)); // Will return 6;
void
  • 36,090
  • 8
  • 62
  • 107
1

try this

.slice(-1)[0]

or

.slice(-1).pop()
Banik
  • 911
  • 6
  • 10
0

By far, voids answer seems to be the most comfortable and shortest one. But if you attempt to use at least one of the numbers at any time again, you may use something like this:

var str = "1,2,3,4,5,6"
str = str.split(',')
var lastNum = str[str.length-1]

As RobG wrote, you could also do

var lastNum = str.pop()
Aer0
  • 3,792
  • 17
  • 33