Interesting. The use of the constructor is new to me. MDN states the following:
There are two ways to create a RegExp object: a literal notation and a constructor.
The literal notation’s parameters are enclosed between slashes and do not use quotation marks.
The constructor function’s parameters are not enclosed between slashes but do use quotation marks.
The following three expressions create the same regular expression object:
let re = /ab+c/i; // literal notation
let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument
let re = new RegExp(/ab+c/, 'i') // constructor with regular expression literal as first argument (Starting with ECMAScript 6)
The literal notation results in compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won’t be recompiled on each iteration.
The constructor of the regular expression object—for example, new RegExp('ab+c') —results in runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don’t know the pattern and obtain it from another source, such as user input.
Thank you! I guess putting the “-” inside the square brackets of the second group might solve that problem.
Someone also pointed out during the stream that this exercise does not validate actual US phone numbers, that the area code and the exchange part cannot start with 0 or 1. But that wasn’t the scope of this exercise, anyway, so that’s fine!
Sure!
The reason I used “?” is that the space character or the hyphen is optional after “1”.
So, the number could be 1 555 555 5555, or 1-555-555-555, or 1 5555555555, etc.
Another way to put it, if there is “1”, there might be a space character or a hyphen following after it. That is optional.
* is a wildcard character that matches zero or more characters preceding it. For example, \d{3}[-\s]* would match a three-digit number that might be followed by a hyphen, or a space character after it. That is again, kind of like optional.
Now I realize that I could’ve actually used “?” after two of the [-\s] parts instead of *, since it could either be a hyphen or space character, but not both. As “?” matches zero or one characters preceding it, this would make better sense. So , something like 1 555- 555- 5555 wouldn’t be allowed.
After reviewing my notes, watching the vid a bit, and getting stuck with using the [ ] or ( ) to group patterns, I finally came up with a solution using regex
(and they say give the task to a lazy person bc it will be done sooner through easier ways )
Solution 2
function telephoneCheck(str) {
let regex = /^(1\s?)?(\(\d{3}\)|\d{3}\-|\d{3})\s?(\d{3}\-|\d{3})\s?\d{4}$/;
return regex.test(str);
}