0

string input:

"12 apples, 3 oranges, 10 grapes"

solution:

let arr= inputString.split(" ");

issue to solve:

how would I go about splitting with anything that isn't a number?

string examples:

  • no spaces

    • 12apples,3oranges,10grapes
  • numbers that are inside ()

    • there are some (12) digits 5566 in this 770 string 239 (i want only 12, 5566, 770, 239)
  • string of numbers having math done on them

    • 33+22 (should be split into 33 and 22)

what i thought could work:

arr= inputString.split("isNaN");

jgrewal
  • 342
  • 1
  • 10
  • 2
    Why do you need to *split*? It seems like you'd want to do the exact opposite and *match* items that are *only numbers*. – VLAZ Dec 16 '21 at 07:14
  • This might help: https://stackoverflow.com/a/10003709/17175441 – aerial Dec 16 '21 at 07:25

3 Answers3

1

You could use a regular expression:

const str = '12apples,3oranges,10grapes';

const splitString = str.match(/(?:\d+\.)?\d+/g);

console.log(splitString);
0

let str = "12apples,3oranges,10grapes"

console.log(str.split(/[^\d]/g).filter(e => e))

str = "there are some (12) digits 5566 in this 770 string 239"

console.log(str.split(/[^\d]/g). filter(e => e))

str="33+22"

console.log(str.split(/[^\d]/g). filter(e => e))

Alan Omar
  • 4,023
  • 1
  • 9
  • 20
0
let str = "12 apples, 3 oranges, 10 grapes"
let arr = str.match(/\d+(.\d+)?/g)
console.log(arr)
Caulic
  • 86
  • 4