How to identify if string is a phone number, Email address or a web address in Javascript? RRS feed

  • Question

  • User1518317647 posted

    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

    Monday, February 18, 2019 1:49 AM

All replies

  • User839733648 posted

    Hi CSharpDeveloper2019,

    According to your description, I suggest that you could use Regular Expressions to meet your requirement.

    Here is a sample.

    var str1 = "John@gmail.com";
    var str2 = "www.google.com";
    var patt = new RegExp("^([A-Za-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$");
    var res1 = patt.test(str1);
    var res2 = patt.test(str2);

    Pay attention to the following points.

    • Using new RegExp() to create a regular expression object for matching text with a pattern.
    • Using .test() method to judge if the string is matched. The result always may be true or false.

    The Regular Expressions of your examples.

    "www.google.com" --> ^(www)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
    "602.123.1778"       --> ^[0-9]{3}.[0-9]{3}.[0-9]{4}$
    "John@gmail.com" -->^([A-Za-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$

    You could refer to this link to check your Regular Expressions: https://regex101.com/ 

    Other References:

    RegExp: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp 

    RegExp.prototype .test():  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test 

    Best Regards,



    Tuesday, February 19, 2019 3:17 AM