Search code examples
javascriptarraysstringconditional-statementsdry

My string check doesnt work and I dont know what is the most eficient method to do it


So I have a code to check if a string matches a certain pattern, this pattern:

555-555-5555
(555)555-5555
(555) 555-5555
555 555 5555
5555555555
1 555 555 5555

for exemple this should return true:

1 456 789 4444

but it doesnt here's my code:

function telephoneCheck(str) {
  str = str.split('');
  for (let c in str) {
    if (str[c].match(/[0-9]/) && str[c] !== '5') {
      str.splice(c, 1, 5);
      console.log(str)
    }
    if (str.join('') === '555-555-5555' |str.join('') === '(555)555-5555' |str.join('') === '(555) 555-5555' |str.join('') === '555 555 5555' |str.join('') === '5555555555' |str.join('') === '5 555 555 5555') {
      return true
    }
    return false
  }
}

console.log(telephoneCheck("1 456 789 4444"));

and as you can see the way I did it is DRY

I was especting for when it matched the patters to return true else false, I dont know for sure whats hapening actualy


Solution

  • I would recommend the tool regex101 for you:

    function telephoneCheck(str) {
        const pattern = /^(1\s?)?(\(\d{3}\)|\d{3})([\s\-]?)\d{3}([\s\-]?)\d{4}$/;
        return pattern.test(str);
    }
    
    console.log(telephoneCheck("1 456 789 4444")); // true