0

Say I have the following string or one like it:

var sentence = "Hey, I got 3 apples today from the 2 food stalls I was told about by 4chan. I'll give you one in a minute or 20."

and I want the following array from it:

var num_array = some_magic_function(sentence); // Contains: {3, 2, 4, 20}

I was looking at splitting by spaces, but that won't get numbers blended in. I can't do number by number because if a number has multiple digits, that's a problem.

lilHar
  • 1,735
  • 3
  • 21
  • 35

1 Answers1

3

You can use a regex to handle this.

var num_array = sentence.match(/\d+/g).map(Number)
Gabriel
  • 621
  • 7
  • 19