Adam91Holt Adam91Holt - 3 months ago 9
Javascript Question

Getting the last bit of string before the whitespace

So say I have the following strings...

"AUDI A4, S4, RS4 4DR SEDAN, WAGON 95-01"
"AUDI 80, 90 4DR SEDAN 86-"
"AUDI A6, 100 QUATTRO 4DR SEDAN, WAGON 92-"
"AUDI A4, S4 (B6,B7) QUATTRO 4DR SEDAN, WAGON 01-08"


I basically want to get the last digits from the string in JavaScript like...

It would be even better if I could split the string into an array or strings.

"95-01"
"86-"
"92-"
"01-08"


Does anyone know how this is possible? I know how to do it from the start like...

str.substr(0,str.indexOf(' '));
str.substr(str.indexOf(' ')+1);


However i'm not sure how to get the end :(

Answer

You can split on whitespace character and get last element as bunch of digits that you want.

var arr =  str.split(' ');
var digits = arr[arr.length-1];