skip to Main Content

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


  1. 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:

    const str = 'id is 12345';
    
    let num = '';
    
    for(const char of str){
      if(!isNaN(parseInt(char))){
        num += char;
      }else if(num){
        break;
      }
    }
    
    console.log(+num);

    If you need to find all numbers you could use Array::reduce() since there’s no breaking loop or wasted looping to the end:

    const str = 'id is 12345 or 54321';
    
    const nums = [...str, ''].reduce(({nums, num}, char) => {
      isNaN(parseInt(char)) ? num && nums.push(+num) && (num = '') : num +=char;
      return {nums, num};
    }, {nums:[], num: ''}).nums;
    
    console.log(nums);
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search