-3

I have a string like

count-contribute-1
count-contribute-11
count-contribute-1111

Here I want to split the string and get the last split value (i.e 1 , 11, 1111);

How can I do it?

mad
  • 3,493
  • 4
  • 23
  • 31
monda
  • 3,809
  • 15
  • 60
  • 84
  • it's unclear what the OP want exactly. but got voted up continue – Bhojendra Rauniyar Apr 01 '14 at 11:59
  • Though not a good solution, just to add there is a way like `var string = "count-contribute-1"; string.substring(string.lastIndexOf('-')+1, string.length)` – Praveen Apr 01 '14 at 12:02
  • possible duplicate of [How to get the last part of a string in JavaScript?](http://stackoverflow.com/questions/6165381/how-to-get-the-last-part-of-a-string-in-javascript) – Qantas 94 Heavy Apr 01 '14 at 12:17
  • possible duplicate of [How do I split this string with JavaScript?](http://stackoverflow.com/questions/96428/how-do-i-split-this-string-with-javascript) – John Dvorak Apr 01 '14 at 12:26

3 Answers3

6

split() on - and pop() of the last value

string.split('-').pop()
adeneo
  • 312,895
  • 29
  • 395
  • 388
2

Use .pop() to get the last item from the array created by .split()

"count-contribute-1".split('-').pop();
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

Also you can get last part of numbers using regular expression. Like this:

s = "count-contribute-111"
s.match(/\d+$/)
//return "111"

It doesn't matter what separator you use.

s = "count-contribute-+*%111"
s.match(/\d+$/)
//return "111"
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43