skip to Main Content

Can anyone help me to turn this string into an array of numbers without losing zeros(0)? And not using regExp

"00ghj67 h4 h000ytff700jhjk80" -> [0,0,67,4,0,0,0,700,80]

function extractNumbers(string) {
    let arrNumbs = [];
    let numbers = "";
    for (let i = 0; i < string.length; i++) {
        let elem = string.charAt(i);
        if (!isNaN(elem)) {
            numbers += elem;
        } else if (numbers !== "") {
            arrNumbs.push(parseInt(numbers));
            numbers = "";
        }
    }
    if (numbers !== "") {
        arrNumbs.push(parseInt(numbers));
        return arrNumbs;
    }
    return arrNumbs;
}
extractNumbers("00ghj67 h4 h000ytff700jhjk80");
console.log(extractNumbers(string)); //->[ 0, 67, 4, 0, 700, 80 ] 

5

Answers


  1. You can add a special case for 0.

    function extractNumbers(string) {
        let arr = [], curr = "";
        function add() {
          if (curr) arr.push(+curr), curr = "";
        }
        for (const c of string) {
          if (!curr && c === '0') arr.push(0);
          else if (isNaN(c)) add();
          else curr += c;
        }
        add();
        return arr;
    }
    console.log(extractNumbers("00ghj67 h4 h000ytff700jhjk80"));
    Login or Signup to reply.
  2. The problem is that parseInt(numbers) will skip the leading zeros. So you have to handle it in a special case. I have modified your code.

    function extractNumbers(string) {
      let arrNumbs = [];
      let numbers = "";
      for (let i = 0; i < string.length; i++) {
        let elem = string.charAt(i);
        // if it's zero, add it and reset numbers 
        // this will handle leading zeros
        if (numbers === "0") {
          arrNumbs.push(0);
          numbers = "";
        }
        if (!isNaN(elem)) {
          numbers += elem;
        } else if (numbers !== "") {
          arrNumbs.push(parseInt(numbers));
          numbers = "";
        }
      }
      if (numbers !== "") {
        arrNumbs.push(parseInt(numbers));
        return arrNumbs;
      }
      return arrNumbs;
    }
    
    Login or Signup to reply.
  3. Turn the input string into an array of individual characters using the spread operator. Then, in the accumulator array of reduce, start a new string whenever we reach a digit directly after a non-digit (and also when a string containing only zero is followed by another zero). Then, for numeric characters, append it to the most recent string in the accumulator array. Finally, use the + operator to coerce the the array of strings into an array of numbers.

    const isNum = c => c>='0' && c<='9'
    
    console.log([...'00ghj67 h4 h000ytff700jhjk80'].reduce((a,c,i,r) => (
      (a[a.length-1]==='0' && c==='0' || isNum(c) && i && !isNum(r[i-1]))
      && a.push(''), isNum(c) && (a[a.length-1] += c), a), ['']).map(i => +i))
    Login or Signup to reply.
  4. But if anyone is looking for regexp instead:

    function extractNumbers (str) {
        return str.match(/0|[1-9]d*/g).map(v => +v);
    }
    console.log(extractNumbers('00ghj67 h4 h000ytff700jhjk80'));
    Login or Signup to reply.
  5. a shorter one:

    document.write(JSON.stringify(extractNumbers('00ghj67 h4 h000ytff700jhjk80')));
    
    function extractNumbers(str)
      {
      let arr = [], sNum = '';
      for (const c of str + '_')
        {
        if      (c==='0' && !sNum)  arr.push(0);
        else if (!isNaN(c))         sNum += c.trimEnd();
        else if (!!sNum)
          {
          arr.push(parseInt(sNum,10));
          sNum = '';
          }
        }
      return arr;
      }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search