dimanche 7 août 2016

Function to extract numbers only from a string

I have written a function that I want to take in a string and then return a string that contains only the number characters from the original string. It

function pureNumbers() {
      var result;
      for (var i = 0; i < phoneNumber.length; i++) {
         if (Number(phoneNumber[i]) !== NaN) {
            result ? result = result + phoneNumber[i] : result = phoneNumber[i]
         }
      }
      return result;
   }

pureNumbers('(123) 456-7890')

Desired result:

result: '1234567890'

What I actually get is:

result: 'undefined(123) 456-7890'

I know there's two issues here (possibly more).

  1. The undefined at the beginning of my result is because my function is attempting to return the value of result in the first loop's iteration, before anything has been assigned to it. I set up the ternary conditional to cover this, not sure why it's not working...
  2. My first if() conditional is intended to make the given character of the string be added to result only if it is a number, yet every single character is being added.

Any help appreciated - thanks in advance.

Aucun commentaire:

Enregistrer un commentaire