gpt4 book ai didi

javascript - 我需要此代码来检查数字

转载 作者:行者123 更新时间:2023-12-02 06:56:16 25 4
gpt4 key购买 nike

var tel = "123457890";
if (tel.length != 10) {
console.log("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
console.log("(" + areaCode + ") " + prefix + "-" + suffix);
}

除了我不能让它只检查数字外,这一切都对我有用。当我根据建议对其进行故障排除并通过 http://repl.it/languages/JavaScript 运行它时我遇到了错误消息。

即当我在 10 位数字的字符串中输入“w”时,我希望它返回“抱歉,格式不正确”,就好像我输入了错误数量的数字等。

最佳答案

您可以使用正则表达式:

var tel = "123457890";
if (!tel.match(/^\d{10}$/)) {
console.log("Sorry, incorrect format.");
} else {
var areaCode = tel.substring(0,3);
var prefix = tel.substring(3,6);
var suffix = tel.substring(6,10);
console.log("(" + areaCode + ") " + prefix + "-" + suffix);
}

关于javascript - 我需要此代码来检查数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com