Sometimes we may be in need of extracting numbers from random strings containing alphabets or symbols. This is more useful if some form validation fails and you absolutely need to numeric values but a user submitted some invalid values with alphabets, numbers and symbols.
We can use our good old regex to the rescue.
Let’s have a look at how we can do that.
let str = "ga123-u45-t-67-a890m";
matches = str.match(/\d+/g);
console.log(matches)
let matchedNumbersString = ''
matches.forEach(m => {
matchedNumbersString += m
})
const matchedNumbersNumber = Number(matchedNumbersString)
console.log(matchedNumbersNumber)
console.log(typeof matchedNumbersNumber)
//output
[ '123', '45', '67', '890' ]
1234567890
number
Code language: JavaScript (javascript)
In the above code, consider str is some user input containing random characters, symbols and numbers. We just want to know the numbers it has.
In line 2, we’ve collected all the global matches for “digits” in the string. At this point, if we console.log(matches), we’d get an array of numbers. Keep in mind though, that this array contains numbers in string form only.
Next, using a loop, we can concatenate all these strings into a single number. Even at this point, it’s a single string.
We can then convert the string to a number using the Number() constructor.