2

I am a beginner with regular expressions. Can anyone please help me to split an email address value which is being entered by the user in the input box. For example, from example@abc.com I want to grab "example" and "www.abc.com" using a Regular expression. Currently I am using the following auto complete code:

var autoCompleteOptions = {
    url: function(phrase) {
      if (phrase.match(/\./)) {
        var newMatch = /^(?:https?:\/\/)?(?:www\.)?(.*)/.exec(phrase);
        phrase = newMatch[1].replace(/\..*/, "");
      }
    },
Patrick
  • 5,526
  • 14
  • 64
  • 101
Victor
  • 67
  • 1
  • 11
  • Input type="email" and phrase.split("@") would be much easier – bigless Dec 27 '17 at 05:40
  • @bigless thanks for your response. After splitting the email can i get the values like as below: var username = parts[0]; var domain = parts[1]; – Victor Dec 27 '17 at 05:42

1 Answers1

1

Suppose the email address entered by a user is stored in a variable email, you can use the following code to split the username and domain part.

var email = "example@abc.com";
var match = email.match(/(.*)@(.*)/);
var username = match[1];
var domain = match[2];

If you want to prepend www at the beginning of the domain, add the following line.

domain = 'www.' + domain;

Alternatively, you can use the JavaScript split() function to implement the same without RegEx.

var email = "example@abc.com";
var parts = email.split('@');
var username = parts[0];
var domain = parts[1];

EDIT

Since the username section in the email can get complex, the above solution can fail in certain cases. For complete email validation, complex RegEx need to be used. Ref

However, for the issue that this question raises, a simple solution can be implemented based on the fact that domain names cannon contain @ symbol.

The below code should work in all the cases.

var email = "example@abc.com";
var parts = email.split('@');
//The last part will be the domain
var domain = parts[parts.length - 1];
//Now, remove last part
parts.pop();
//Everything else will be username
var username = parts.join('@');
Vivek
  • 2,665
  • 1
  • 18
  • 20
  • Just wanted to let you know that this does not work for all valid emails. For example : `"email@"@example.com`. If you don't believe me look at other pages on Stackoverflow about the crazy email spec. – Greenbeard Dec 27 '17 at 07:24
  • @Greenbeard Yes, I agree.. There are many cases where this solution might fail theoretically. But the fact is most major email providers doesn't allow such special characters in their email id. On new browsers, even `` doesn't consider your example as valid. – Vivek Dec 27 '17 at 07:34
  • @Victor See the updated code. It should work in every scenario. – Vivek Dec 27 '17 at 10:49