如何检查String是否以javascript中的数字开头

如何检查String是否以javascript中的数字开头

本文介绍了如何检查String是否以javascript中的数字开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚用户是否输入了电子邮件ID或电话号码。因此,我想检查字符串是否以+1或数字开头,以确定它是否是电话号码。如果它不是我得出结论它是一个电子邮件或我可以检查它是否以字母表开头确定。我该如何检查。如果那是soln,我对正则表达式很可怕。

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 .

推荐答案

你可以用RegEx做到这一点,但是一个简单的if语句可以工作同样,并且可能更具可读性。如果字符串中不存在 @ 字符,并且第一个字符是数字,则可以合理地假设它是电话号码。否则,它可能是一个电子邮件地址,假设存在 @ 。否则,它可能是无效输入。 if语句如下所示:

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:

if(yourString.indexOf("@") < 0 && !isNaN(+yourString.charAt(0) || yourString.charAt(0) === "+")) {
    // phone number
} else if(yourString.indexOf("@") > 0) {
    // email address
} else {
    // invalid input
}

这篇关于如何检查String是否以javascript中的数字开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:41