Given the following email address -- [email protected] -- how can I extract someone from the address using javascript?
Thank you.
Given the following email address -- [email protected] -- how can I extract someone from the address using javascript?
Thank you.
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
str.split("@").reduce(user => user)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.."[email protected]".split('@')[0]
username:
"[email protected]".replace(/^(.+)@(.+)$/g,'$1')
server:
"[email protected]".replace(/^(.+)@(.+)$/g,'$2')
You can generate or fetch a username from the email with the help of this npm package.
2. npm i generate-username-from-email
const generateUsername = require('generate-username-from-email')
var email = "[email protected]"
var username = generateUsername(email)
console.log(username)
//Output: patidarparas13
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.
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]'))
The example code below will return myemailaddress.
getUsername = (email) => {
return email.substring(0, email.lastIndexOf("@"));
}
const userEmail = '[email protected]';
getUsername(userEmail);
// 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;
}
}
I have created a npm package to extract name from email. Please checkout here.