Having issue with telephone validator even though regex101 says it should be true

Tell us what’s happening:
This is the test for the telephone number validator. I’m using regex to do it and it works on most of the tests but three are failing and I don’t understand why. According to https://regex101.com/ it works as true on the three it fails both in freecodecamp and codepen.io. Not sure what I might be doing wrong.

Here’s the codepen failure https://codepen.io/drewhosick/pen/qBXNJyE?editors=1111
Here’s the regex101 thingy regex101: build, test, and debug regex
I don’t see why it shouldn’t work. It must have something to do with the ( ) escapes or something but I don’t get it.

  **Your code so far**

function telephoneCheck(str) {
let regexTest = new RegExp("^1? ?([0-9]{3}|\([0-9]{3}\))-? ?[0-9]{3}-? ?[0-9]{4}$");
return regexTest.test(str);

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36

Challenge: Telephone Number Validator

Link to the challenge:

When you use a string to create a new RegExp you need to escape the backslashes (because a backslash has a special meaning in a string), so if you make it \\( and \\) and then it will pass.

But I don’t need to escape backslashes. I’m using them to escape paranthesis. ( )

Oh shoot. Because it’s in javascript you mean? that would make sense sort of. I would have thought it would work inside of string though

In a string, the backslash is an escape character and is used to create special characters, such as “\n” which stands for newline. Thus, if you want to actually have an actual backslash in a string you need to use "\\". So if you want to have \( in the regexp, since you are using a string to create it, you have to do \\(, which then converts to \( in the string.

And this isn’t specific to JS. Other languages use the backslash as the escape character. The \n newline sequence is pretty standard.

Yes thanks. Figured it out after trying it and then figured out I could also use regex literal instead to avoid the issue altogether. Appreciate the tip

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.