Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if String starts with number in javascript

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 .

like image 343
vijar Avatar asked Jan 27 '14 22:01

vijar


3 Answers

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
}
like image 152
Elliot Bonneville Avatar answered Nov 02 '22 23:11

Elliot Bonneville


if (!isNaN(parseInt(yourstrung[0], 10))) {
  // Is a number
}
like image 39
Nikola Mitev Avatar answered Nov 02 '22 23:11

Nikola Mitev


Just do the following:

if ( !isNaN(parseInt(inputString)) ) {
    //this starts with either a number, or "+1"
}
like image 22
Joeytje50 Avatar answered Nov 02 '22 23:11

Joeytje50