0

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+]/);
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
webHasan
  • 461
  • 3
  • 11
  • What is your hosting language for regex? This does not look like anything related to `NSRegularExpression` – Sergey Kalinichenko Jan 16 '18 at 13:40
  • 1
    the `+` is not a character you want to match, i guess, try `/[^\d]+/` (but you'll have an empty first array element, and also the last one if you put text after the 8) – Kaddath Jan 16 '18 at 13:40
  • @dasblinkenlight Yes, It is my mistake. It should be /[^\d]+/ – webHasan Jan 16 '18 at 14:18
  • 1
    Why don't you just use `\d+`? It'll get you all the numbers – ctwheels Jan 16 '18 at 14:28
  • @ctwheels Actually wanted to do this by JavaScript split method. – webHasan Jan 16 '18 at 14:47
  • @webHasan is there a reason why? I mean, just doing a match on the numbers would be much more effective and likely faster. – ctwheels Jan 16 '18 at 15:02
  • @ctwheels match method is a perfect way, I am learning JavaScript and just tried to accomplish it by split method. I did not get the expected result that's why from my curiosity I posted the question. Thanks – webHasan Jan 16 '18 at 15:54

1 Answers1

1

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);
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117