I like to collect digits into an array from a string. I tried following way but not getting an expected result in Javascript. How can I do this?
'This is string 9, that con 9 some 12, number rally awesome 8'.split(/[^\d+]/);
I like to collect digits into an array from a string. I tried following way but not getting an expected result in Javascript. How can I do this?
'This is string 9, that con 9 some 12, number rally awesome 8'.split(/[^\d+]/);
I'm assuming this is JavaScript not Swift.
'This is string 9, that con 9 some 12, number rally awesome 8 extra'.
split(/[^\d]+/);
produces
[ '', '9', '9', '12', '8', '' ]
As you can see, it gets you most of the way there, however there is a possible leading and possible trailing empty string.
Filter can solve this problem.
'This is string 9, that con 9 some 12, number rally awesome 8 extra'.
split(/[^\d]+/).
filter(function(number) { return number.length > 0 });
produces the answer you are looking for.
[ '9', '9', '12', '8' ]
Or if you are using ES6.
'This is string 9, that con 9 some 12, number rally awesome 8 extra'.
split(/[^\d]+/).
filter(number => number.length > 0);