简体   繁体   中英

How to grab the content before and after an email domain like @ using Regular expression

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(/\..*/, "");
      }
    },

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('@');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM