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