0

Why doesn't my return within the IF work?

function telephoneCheck(str) {
  var a;
  let result = false;
  let str1 = str.split("");
  if (
    str1[0].isInteger === true &&
    str1[1].isInteger === true &&
    str1[2].isInteger === true &&
    str1[3] === "-" &&
    str1[4].isInteger === true &&
    str1[5].isInteger === true &&
    str1[6].isInteger === true &&
    str1[7] === "-" &&
    str1[8].isInteger === true &&
    str1[9].isInteger === true &&
    str1[10].isInteger === true &&
    str1[11].isInteger === true
  ) {
    return true;
  }
}
telephoneCheck("555-555-5555");
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179

3 Answers3

0

Your code is not working because Number.isInteger() should be used as follows:

Number.isInteger(5) //true
Number.isInteger(4.3) //false
Numbers.isInteger('5') //false

Now, for your code to work, you need to check this way

Number.isInteger(parseInt(str[i])) === true //which is not really necessary
Number.isInteger(parseInt(str[i])) //is enough

While this works, there are more neat ways to write the function you need. Try learning about regex or even a foreach would do the job.

Ahmed Hammad
  • 2,798
  • 4
  • 18
  • 35
  • Ahmed, but even the right way of using isInteger would not bring the expected result, as he is spliting strings in the end of the day. Check my answer. – Pedro Coelho May 10 '20 at 04:28
  • @PedroCoelho Yes, `isInteger()` doesn't work with strings, that's why I used `parseInt()` to fix it. This is not efficient, but the pal seems to be yet kicking off, so let's just give it him step by step. – Ahmed Hammad May 10 '20 at 19:48
0

If I were you, I would use isNaN to check if str1[index] is a number, since it also checks if there is a number as string (which is the case in your example). Note that Number.isInteger(value) will return false for any string, even if there is a number as string. Check my suggestion below:

function telephoneCheck(str) {        
    let str1 = str.split("");
    if (
        isNumber(str1[0]) &&
        isNumber(str1[1]) &&
        isNumber(str1[2]) &&
        str1[3] === "-" &&
        isNumber(str1[4]) &&
        isNumber(str1[5]) &&
        isNumber(str1[6]) &&
        str1[7] === "-" &&
        isNumber(str1[8]) &&
        isNumber(str1[9]) &&
        isNumber(str1[10]) &&
        isNumber(str1[11])
    ) {
        return true;
    }
}

function isNumber(input) {
    return !isNaN(input);
}

telephoneCheck("555-555-5555");
Pedro Coelho
  • 1,411
  • 3
  • 18
  • 31
0

isInteger() is a method of the Number() object, so your test to a string will not work, you could cast the string to a number but you might lose the meaning of the validation.

another way is to check using a regular expression test

replace: str1[0].isInteger === true &&

with: /[0-9]/.test(str1[0]) &&

This will check if the string provided is a digit between 0 and 9

Hugo Avila
  • 46
  • 5