Skip to content Skip to sidebar Skip to footer

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 phon

Solution 1:

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
} elseif(yourString.indexOf("@") > 0) {
    // email address
} else {
    // invalid input
}

Solution 2:

if (!isNaN(parseInt(yourstrung[0], 10))) {
  // Is a number
}

Solution 3:

Just do the following:

if ( !isNaN(parseInt(inputString)) ) {
    //this starts with either a number, or "+1"
}

Solution 4:

Might I suggest a slightly different approach using the regex email validation found here?

if(validateEmail(input_str)) {
    // is an email
} elseif(!isNaN(parseInt(input_str))) {
    // not an email and contains a number
} else {
    // is not an email and isn't a number
}

functionvalidateEmail(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.

Post a Comment for "How To Check If String Starts With Number In Javascript"