Using a RegExp instance, write a JavaScript function isValid() that accepts a String argument and returns true if the argument matches one of the following phone-number formats and returns false otherwise: (123)456-7890 (123) 456-7890 123/456-7890 123-456
时间: 2023-06-16 21:07:53 浏览: 55
Here's an example implementation of the `isValid` function that uses a regular expression to check for the valid phone number formats:
```javascript
function isValid(phoneNumber) {
// Regular expression to match valid phone number formats
var regex = /^(\(\d{3}\)|\d{3})[\/\- ]?\d{3}[\/\- ]?\d{4}$/;
// Check if the phoneNumber matches the regular expression
return regex.test(phoneNumber);
}
```
Explanation of the regular expression:
- `^`: Matches the start of the string.
- `(\(\d{3}\)|\d{3})`: Matches either an opening bracket followed by three digits and a closing bracket, or just three digits. The parentheses are escaped with a backslash because they have special meaning in regular expressions.
- `[\/\- ]?`: Matches an optional forward slash, hyphen, or space.
- `\d{3}`: Matches three digits.
- `[\/\- ]?`: Matches an optional forward slash, hyphen, or space.
- `\d{4}`: Matches four digits.
- `$`: Matches the end of the string.
This regular expression matches the following phone number formats:
- `(123)456-7890`
- `(123) 456-7890`
- `123/456-7890`
- `123-4567890`
Note that spaces are also allowed between the area code and the phone number, and between the first three and last four digits of the phone number.