0

How to get numbers separated by any delimiter (space or any non numeric character).

I tried Input string: "111,256 323| 78987 & 6543".split(/,| /),

but then it requires me to specify the delimiter. What Regex can I use to split the numbers and get like [111, 256, 323, 78987, 6543]

keerti
  • 245
  • 5
  • 19
  • 2
    Does this answer your question? [How can I extract a number from a string in JavaScript?](https://stackoverflow.com/questions/10003683/how-can-i-extract-a-number-from-a-string-in-javascript). Scroll down and you'll find answers on how to extract multiple. – kelsny Sep 24 '22 at 23:15

2 Answers2

3

You can try this :

let numberPattern = /\d+/g;
let numbersArr = "111,256 323| 78987 & 6543".match(numberPattern)
console.log(numbersArr)

The result must be like that : click here

Abdullah Musa
  • 44
  • 1
  • 5
2

To split by non numeric characters:

"111,256 323| 78987 & 6543".split(/[^\d]+/)

If you want to keep decimals:

"111,256 323| 78987 & 6543".split(/[^0-9.]+/)

If on top of that you want to get an array of numbers, map the strings to numbers:

"111,256 323| 78987 & 6543".split(/[^\d]+/).map(n => Number(n))
user3252327
  • 617
  • 5
  • 9