Link to home
Start Free TrialLog in
Avatar of maccaj51
maccaj51Flag for Afghanistan

asked on

Jquery/JS : How to detect a telephone number or email within a string?

Hi Experts,

I am grabbing the value of a textarea on blur and want to see whether it has an email address ( and/or a telephone number (0123456780 or 01234 567890)

Any help would be really well received
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

How much validation do you need?  Can you just look to see if there is an @ sign for instance and if that is the case, call it an email else call it a phone number?  Or do you need more detailed algo for email and phone as in it could be neither (ie 5 digit number).

The simple example may be
var string = "";
var isEmail = string.includes("@");
// treat as email
} else {
 // treat as phone

Open in new window

You may want to do additional validation though.
Avatar of maccaj51


Hi There,

Thanks for answering so quick. I need to detect if both are present - not either or.

I've found this for emails which seems half decent as a starting point

function extractEmails (text)
    return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

Open in new window

There is one text field to test, right?,output
<!DOCTYPE html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <input id="test" placeholder="start here">
  <input placeholder="tab to here">
<script src=""></script>
     var testValue = $('#test').val();

function detect(str){
    return "email";
  } else {
    return "phone";



Open in new window

I am not well versed in regular expressions but you can play with that as well.  The logic will still be similar.  There are going to be multiple ways to get to the same thing here.
I'm sorry, I didn't read your question correctly.  You are saying there could be both and you need to extract both if available.
Yes - correct
Avatar of Scott Fell
Scott Fell
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Scott