Tell us what’s happening:
Im stuck on my regex expression. I have 2 forms of code and 3 stories that won’t pass, if someone could guide me pls:
Code A: ^(1[\s-]?)?\d{3}[\s-]?\d{3}[\s-]?\d{4}$
When the #user-input element contains 1 (555) 555-5555 and the #check-btn element is clicked, the #results-div element should contain the text “Valid US number: 1 (555) 555-5555”.
-
When the #user-input element contains (555)555-5555 and the #check-btn element is clicked, the #results-div element should contain the text “Valid US number: (555)555-5555”.
-
When the #user-input element contains 1(555)555-5555 and the #check-btn element is clicked, the #results-div element should contain the text “Valid US number: 1(555)555-5555”.
To fix this I added an optional open and close parenthesis which solves this but a different 3 stories fail…
Code B: /^(1[\s-]?)?(?\d{3})?[\s-]?\d{3}[\s-]?\d{4}$/g; fails // running tests
15. When the #user-input element contains 1 555)555-5555 and the #check-btn element is clicked, the #results-div element should contain the text “Invalid US number: 1 555)555-5555”.
30. When the #user-input element contains 555)-555-5555 and the #check-btn element is clicked, the #results-div element should contain the text "In
Your code so far
/* file: script.js */
const userInput= document.getElementById("user-input");
const checkBtn= document.getElementById("check-btn");
const clearBtn= document.getElementById("clear-btn");
const resultsDiv= document.getElementById("results-div");
checkBtn.addEventListener("click", () => {
const numRegex= /^(1[\s-]?)?\d{3}[\s-]?\d{3}[\s-]?\d{4}$/g;
const input= userInput.value;
if(userInput.value === ""){
alert("Please provide a phone number")
}
else if (numRegex.test(input)){
resultsDiv.innerHTML= `Valid US number: ${userInput.value}`
}
else {
resultsDiv.innerText= `Invalid US number: ${userInput.value}`
}
return
});
clearBtn.addEventListener("click", ()=> {
resultsDiv.innerHTML= ""
})
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0
Challenge Information:
Build a Telephone Number Validator Project - Build a Telephone Number Validator
TO