javascript 如何在javascript中检查字符串是否以数字开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21393027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if String starts with number in javascript
提问by vijar
I am trying to figure out if a user has entered an email id or a phone number. Therefore i would like to check if the string starts with +1 or a number to determine if it is a phone number . If it is not either i come to the conclusion it is an email or i could check if it starts with a alphabet to be sure. How do i check this . I am horrible with regex if that is the soln .
我想弄清楚用户是否输入了电子邮件 ID 或电话号码。因此,我想检查字符串是否以 +1 或数字开头,以确定它是否是电话号码。如果不是,我得出结论,它是一封电子邮件,或者我可以检查它是否以字母开头以确保。我如何检查这个。如果那是解决方案,我对正则表达式感到很糟糕。
回答by Elliot Bonneville
You can do this with RegEx, but a simple if statement will work as well, and will likely be more readable. If an @
character is not present in the string and the first character is a number, it is reasonable to assume it's a phone number. Otherwise, it's likely an email address, assuming an @
is present. Otherwise, it's likely invalid input. The if statement would look like this:
您可以使用 RegEx 执行此操作,但简单的 if 语句也可以使用,并且可能更具可读性。如果@
字符串中不存在字符且第一个字符是数字,则可以合理地假设它是电话号码。否则,它可能是一个电子邮件地址,假设@
存在。否则,很可能是无效输入。if 语句看起来像这样:
if(yourString.indexOf("@") < 0 && !isNaN(+yourString.charAt(0) || yourString.charAt(0) === "+")) {
// phone number
} else if(yourString.indexOf("@") > 0) {
// email address
} else {
// invalid input
}
回答by Nikola Mitev
if (!isNaN(parseInt(yourstrung[0], 10))) {
// Is a number
}
回答by Joeytje50
Just do the following:
只需执行以下操作:
if ( !isNaN(parseInt(inputString)) ) {
//this starts with either a number, or "+1"
}
回答by Samsquanch
Might I suggest a slightly different approach using the regex email validation found here?
我可以建议使用此处找到的正则表达式电子邮件验证的稍微不同的方法吗?
if(validateEmail(input_str)) {
// is an email
} else if(!isNaN(parseInt(input_str))) {
// not an email and contains a number
} else {
// is not an email and isn't a number
}
function validateEmail(email) {
var re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
This way you can check a little more thoroughly on what the input actually is, rather than just guessing it's one or the other.
通过这种方式,您可以更彻底地检查输入的实际内容,而不仅仅是猜测它是其中一个。