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.
2
Answers
Iterate characters and parse each into a number. If the parsing is successful (check with
isNaN()
) then add it to the result number string. If the number sequence ends, break the loop:If you need to find all numbers you could use
Array::reduce()
since there’s no breaking loop or wasted looping to the end: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).