Hi. Do you have a question? I suppose you would like to know why your code is not working? There are a few problems. It might be easier for you to use regex testing websites like https://regex101.com? They provide explanations and syntax highlighting, so you will quickly understand what is wrong with your regex.
Problem 1
The regex on the following line tests if any character is a digit:
if (str.match(/[0-9]/)&& str.length === 10) {
So these strings would all match:
-
number 1!!
contains a number, so it matches
-
123456789!
contains numbers, match
You want to test if all characters are digits:
if (str.match(/^[0-9]+$/) && str.length === 10) {
// or
if (str.match(/^\d+$/) && str.length === 10) {
// or
if (str.match(/^\d{10}$/)) {
Problem 2
I think you should handle the country code, so /^1?\d{10}$/
is probably better (read: maybe a '1', followed by ten digits
).
Problem 3
The regex on the following line contains multiple errors.
else if(str.match(/([0-9]$ ^1 -{0,2} " "{0,3} “(” “)”)) {
- You are using double quotation marks (
"
, ”
and “
) all over the place. They have no special meaning in a regex, so the only character they can match is themselves. I think you want to escape the brackets ((
and )
), but that doesn’t work. The correct way to escape a bracket is like so: \(
and \)
.
- A regular expression should begin and end with a slash* (
/
), but this one does not end properly => syntax error.
- You put
$
before ^
, which means ‘my regex should match when the end occurs before the beginning of a string’. This is impossible. $
must occur after ^
. Also you can’t require any text before the beginning of the string or after the end, so ^
should be first and $
should be last. *
- Like in the previous regex you only check if there is any digit in the string.
- Your use of quantifiers is a bit odd:
-{0,2}
means that you want zero, one or two dashes (-
) in a row. It does not mean that they can occur anywhere within the string. You seem to think that the order in a regex does not matter, but it absolutely does.
Here’s an explanation how to match the format (555)555-5555
:
//explanation: '(' | 3 digits | ')' | 3 digits | '-' | 4 digits
// /^ \( \d{3} \) \d{3} - \d{4} $/
In reality the regex should not contain spaces, so it would be used like this:
str.match(/^\(\d{3}\)\d{3}-\d{4}$/)
You don’t seem to fully understand how regular expressions work, yet. Maybe it helps to go over the lessons again or look elsewhere for a tutorial (in your native language if it’s not English)? This is not a topic that is easy to understand for beginners.
Good luck!
(*: Not strictly true, but I don’t want to complicate things.)