skip to Main Content

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

2

Answers


  1. I would convert it to a regular expression

    const regex = new RegExp(`555-555-5555
    (555)555-5555
    (555) 555-5555
    555 555 5555
    5555555555
    1 555 555 5555`
    .replace(/5/g, '\d')
    .replace(/(/, '\(')
    .replace(/)/, '\)')
    .split('n').join('|')
    )
    
    console.log(regex.test('1 456 789 4444'))
    Login or Signup to reply.
  2. I would recommend the tool regex101 for you:

    function telephoneCheck(str) {
        const pattern = /^(1s?)?((d{3})|d{3})([s-]?)d{3}([s-]?)d{4}$/;
        return pattern.test(str);
    }
    
    console.log(telephoneCheck("1 456 789 4444")); // true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search