Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading