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

Viewed 22

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]

2 Answers

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

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))
Related