29

Given the following email address -- [email protected] -- how can I extract someone from the address using javascript?

Thank you.

1

10 Answers 10

65

Regular Expression with match

with safety checks

var str="[email protected]";
var nameMatch = str.match(/^([^@]*)@/);
var name = nameMatch ? nameMatch[1] : null;

written as one line

var name = str.match(/^([^@]*)@/)[1];

Regular Expression with replace

with safety checks

var str="[email protected]";
var nameReplace = str.replace(/@.*$/,"");
var name = nameReplace!==str ? nameReplace : null;

written as one line

var name = str.replace(/@.*$/,"");

Split String

with safety checks

var str="[email protected]";
var nameParts = str.split("@");
var name = nameParts.length==2 ? nameParts[0] : null;

written as one line

var name = str.split("@")[0];

Performance Tests of each example

JSPerf Tests

Sign up to request clarification or add additional context in comments.

8 Comments

Not sure about javascript semantics, but I would use this pattern: /.+(?=@)/
In a functional manner: str.split("@").reduce(user => user)
@epascarello - Why aren't you (or anyone else here) using a simple str.substring(0,str.indexOf("@"))? Since you have about 65 times as much reputation as me, I'm pretty sure I'm missing something, just don't know what..
@epascarello I like to think I can still learn from a 5 year old question. Same rules still largely apply. And if someone visits this page in 2022, I'd like to think that person can still learn something from your answer to my question.
The link of JSPerf Tests are broken. :-/
|
27
"[email protected]".split('@')[0]

1 Comment

Like the simplicity of the solution
2
var email = "[email protected]";

var username = email.substring(0,email.indexOf('@'))

Comments

1

string.split(separator, limit) is the method you want

"[email protected]".split("@")[0]

Comments

1

username:

"[email protected]".replace(/^(.+)@(.+)$/g,'$1')

server:

"[email protected]".replace(/^(.+)@(.+)$/g,'$2')

Comments

1

You can generate or fetch a username from the email with the help of this npm package.

  1. Generate username from email

2. npm i generate-username-from-email

  1. Use this code to fetch the username from email:
const generateUsername = require('generate-username-from-email')
var email = "[email protected]"
var username = generateUsername(email)
console.log(username)
//Output: patidarparas13

Comments

0

My 2021 update. This will correctly output a username from an email address that contains multiple @ symbols. Just splitting with '@' is not safe as multiple are allowed if quoted.

JSFiddle example

function getUsernameFromEmail(email){
    var domainArray = email.split('@')
    var domain = domainArray[domainArray.length-1]
    var reverseEmail = email.split( '' ).reverse( ).join( '' );
    var reverseDomain = domain.split( '' ).reverse( ).join( '' );
    var backwardUsername = reverseEmail.replace(reverseDomain+'@','')
    var username = backwardUsername.split( '' ).reverse( ).join( '' );
  return username;
}

console.log(getUsernameFromEmail('test@[email protected]'))

1 Comment

if multiple allowed can we split from end? because the last used @ will be correct?
0

The example code below will return myemailaddress.

getUsername = (email) => {
   return email.substring(0, email.lastIndexOf("@"));
}

const userEmail = '[email protected]';
getUsername(userEmail);

Comments

0

// Input: [email protected]. Output: Test User
// Split user email then capitalize each first character of word.

   public getUserName(input: string): string {
         if (!input) {
           return ''
         }
         if (!input.includes('@')) {
           return input;
         } else {
           const cleanedInput = input.split('@')[0]?.replace(/[^\w]/g, ' ').split(' ');
           const capitalizedInput = cleanedInput?.map(word => {
             return word[0]?.toUpperCase() + word.substring(1);
           }).join(' ');
    
           return capitalizedInput;
         }
      }

Comments

0

I have created a npm package to extract name from email. Please checkout here.

https://www.npmjs.com/package/get-name-from-email

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.