Without using regex, is there a way to get number from a string in JavaScript?
For example, if input is "id is 12345", then I want 12345 number in output.
I know a lot of regex solutions, but I am looking for a non-regex tidy solution.
Without using regex, is there a way to get number from a string in JavaScript?
For example, if input is "id is 12345", then I want 12345 number in output.
I know a lot of regex solutions, but I am looking for a non-regex tidy solution.
On
You can loop over all the characters and build up numbers from consecutive digits.
Here is one solution that works for multiple numbers (formed only using the characters 0-9).
const str = "abc def 12345 xyz 987";
let res = [], curr = '';
for (const c of str + ' ') {
if (c >= '0' && c <= '9') // add || c === '-' (to handle negatives)
curr += c;
else if (curr)
res.push(+curr), curr = '';
// use BigInt(curr) to handle larger numbers
}
console.log(res);
Iterate characters and check whether they are in a set of numbers:
If you want the fastest solution use Unmitigated's
c >= '0' && c <= '9'andString::slice():