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).
- The
undefined
at the beginning of myresult
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... - My first
if()
conditional is intended to make the given character of the string be added toresult
only if it is a number, yet every single character is being added.
Any help appreciated - thanks in advance.