EN
JavaScript - get all numbers in string and push them to array
0 points
In this article, we would like to show you how to get all numbers in a string and push them to an array using JavaScript.
Quick solution:
xxxxxxxxxx
1
const text = '1a 2b 3c';
2
const result = text.match(/\d+/g); // ['1', '2', '3']
In this example, we use /\d+/g
regex to extract all numbers from the string to an array.
xxxxxxxxxx
1
const text = '1a 2b 3c';
2
const regex = /\d+/g;
3
4
const numbers = text.match(regex);
5
6
if (numbers) {
7
console.log(JSON.stringify(numbers)); // ['1','2','3']
8
}