如果传递的字符串是有效的美国电话号码,该函数应返回 true。
这取决于您希望它有多“有效”。如果您的意思是它恰好包含 10 位数字,或者包含国家/地区代码的 11 位数字...那么它可能非常简单。
function telephoneCheck(str) {
var isValid = false;
//only allow numbers, dashes, dots parentheses, and spaces
if (/^[\d-()\s.]+$/ig.test(str)) {
//replace all non-numbers with an empty string
var justNumbers = str.replace(/\D/g, '');
var count = justNumbers.length;
if(count === 10 || (count === 11 && justNumbers[0] === "1") ){
isValid = true;
}
}
console.log(isValid, str);
return isValid;
}
telephoneCheck("555-555-5555"); //true
telephoneCheck("1-555-555-5555"); //true
telephoneCheck("(555)5555555"); //true
telephoneCheck("(555) 555-5555"); //true
telephoneCheck("555 555 5555"); //true
telephoneCheck("5555555555"); //true
telephoneCheck("1 555 555 5555") //true
telephoneCheck("2 555 555 5555") //false (wrong country code)
telephoneCheck("800-692-7753"); //true
telephoneCheck("800.692.7753"); //true
telephoneCheck("692-7753"); //false (no area code)
telephoneCheck(""); //false (empty)
telephoneCheck("4"); //false (not enough digits)
telephoneCheck("8oo-six427676;laskdjf"); //false (just crazy)
.as-console-wrapper{max-height:100% !important;}
Google 为全人类提供了一个巨大的帮助,并发布了电话号码验证和格式化库:https://github.com/googlei18n/libphonenumber
就您而言,您可以使用 NPM 上提供的 Javascript 库,网址为 https://www.npmjs.com/package/google-libphonenumber
npm install --save-prod google-libphonenumber
然后
// Get an instance of `PhoneNumberUtil`.
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
// Result from isValidNumber().
console.log(phoneUtil.isValidNumber(number));
// Result from isValidNumberForRegion().
console.log(phoneUtil.isValidNumberForRegion(number, 'US'));
如果传递的字符串是有效的美国电话号码,该函数应返回 true。
好的。我知道它的项目适用于 FreeCodeCamp javaScript 挑战,我建议在尝试此挑战之前阅读并练习更多问题。 这可以通过正则表达式来解决,不需要循环等等。
function telephoneCheck(str) {
let regEx = /^(1?\s?)(\d{3}|[(]\d{3}[)])[-\s]?(\d{3})[-\s]?(\d{4})$/;
return regEx.test(str);
}
telephoneCheck("555-555-5555");