[Validate US phone number] I'm not very proud of what I've done, but I did it! LOL

[Validate US phone number] I'm not very proud of what I've done, but I did it! LOL
0

#1

Guys, I must say that I hated this challenge. Basically I spent hours just brute forcing some crazy regex shit along with some if/else statements, and a crazy for loop… So, I was able to pass the challenge… But man… Talk about !elegancy LOL

Thoughts?

Check it out: https://repl.it/Cjw2/0


#2

I think you over complicated the task, here’s how I sovled it.
function telephoneCheck(str) {
if (isNaN(str[0]) && !isNaN(str[4])) {
return false;
}
str = str.replace(/-|(|)|\s/g, ‘’);
if (!isNaN(str)) {
if (str.length < 10 || str.length === 11 && str[0] != 1) {
return false;
} else if (str.length > 11) {
return false;
}
return true;
}
return false;
}
telephoneCheck(“555-555-5555”);


#3

I get a bunch of red crosses when I try your code :frowning:


#4

Oh seems they changed some stuff since I finished it :slight_smile:


#5

Why wouldn’t you be proud of that? Always be proud of finishing a challenge. If you want to improve it, I would take a look at String.prototype.match and apply your regex-foo to that. Also, if you want an easy way to test your regex, check out regexr.

Well done!


#6

Ok, update code to work with newest additions

function telephoneCheck(str) {
  if (isNaN(str[0]) && !isNaN(str[4]) || str.match(/\d[^-|\d|\s]/g) !== null && str.match(/\(\d+\)/g) === null) {
    return false;
  } else if (str.match(/\(/g) !== null && str.match(/\)/g) === null) {
    return false;
  }
  str = str.replace(/\-|\(|\)|\s/g, '');
  if (!isNaN(str)) {
    if (str.length < 10 || str.length === 11 && str[0] != 1) {
      return false;
    } else if (str.length > 11) {
      return false;
    }
    return true;
  }
  return false;
}

telephoneCheck("555-555-5555");