Skip to content
Advertisement

how to split a string with anything that is not a number

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");

Advertisement

Answer

You could use a regular expression:

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

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

console.log(splitString);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement