How to identify if string is a phone number, Email address or a web address in Javascript?
-
I am calling a third-party API to get customer contact information and it returns a string for each field and my application needs to determine if the string is a phone number or Email or web address
String data=GetCustomerInfoFromAPI() // will get customer contact information from an API call and will return a string
some examples for the data string I am getting back from the API call
"www.google.com"
"602.123.1778"
"John@gmail.com" -
I am calling a third-party API to get customer contact information and it returns a string for each field and my application needs to determine if the string is a phone number or Email or web address
String data=GetCustomerInfoFromAPI() // will get customer contact information from an API call and will return a string
some examples for the data string I am getting back from the API call
"www.google.com"
"602.123.1778"
"John@gmail.com"If the source system does not provide the type then you will need to work it out by trial and error. Assuming that each type will be guaranteed to be in a certain basic form you can use the various JavaScript String Reference[^] methods to parse the strings and check for patterns etc. For example will all telephone numbers contsain only numbers and specific field delimiters? Will all email addresses contain @ characters etc.
-
I am calling a third-party API to get customer contact information and it returns a string for each field and my application needs to determine if the string is a phone number or Email or web address
String data=GetCustomerInfoFromAPI() // will get customer contact information from an API call and will return a string
some examples for the data string I am getting back from the API call
"www.google.com"
"602.123.1778"
"John@gmail.com"I'm probably to late but here is it anyway. You can make use of Regular expression (Regex) to validation your strings. Here is an example on how to check if the string is an email address using regex:
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(String(email).toLowerCase());
}