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
I would convert it to a regular expression
I would recommend the tool regex101 for you: