课程: JavaScript Practice: String Manipulation

Solution: Check phone number format - JavaScript教程

课程: JavaScript Practice: String Manipulation

Solution: Check phone number format

- [Instructor] In this challenge, we need to determine if a US phone number is formatted correctly. We will do this by checking to see that the phone number starts with the appropriate country code. Our function on line 13, isPhoneNumberValid takes the argument of phoneNumber. We will need to check this phone number to see that it starts with the US country code of one. To determine if the phone number starts with 1-, we can use the string method startsWith. The startsWith method has two parameters, the search string that we're looking for and the position that we want to start the search. By default, this is set to zero. If the phone number starts with 1- we'll return the variable valid on line 10 that states Valid Phone Number. If the phone number's not valid, we'll return invalid, the variable on line 11 that states Invalid Phone Number. For this solution, we can make this super clean and use a ternary. So let's get started on line 15, we're going to start with our return and we're going to use phoneNumber, which is what we're checking, and we want to see does phone number starts, and apply that startsWith method, startsWith 1-. All right. So this is going to return true or false. So if the phone number starts with 1- we will return valid, and if not, invalid. All right, let's go ahead and run our test code and see what we get. Awesome work. You can see that our phone number was valid, it started with 1- and so we returned Valid Phone Number. Great work.

内容