简体   繁体   中英

How can I extract the user name from an email address using javascript?

Given the following email address -- someone@example.com -- how can I extract someone from the address using javascript?

Thank you.

Regular Expression with match

with safety checks

var str="someone@example.com";
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="someone@example.com";
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="someone@example.com";
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

"someone@example.com".split('@')[0]
var email = "someone@example.com";

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

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 = "patidarparas13@gmail.com"
var username = generateUsername(email)
console.log(username)
//Output: patidarparas13

username:

"someone@example.com".replace(/^(.+)@(.+)$/g,'$1')

server:

"someone@example.com".replace(/^(.+)@(.+)$/g,'$2')

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@testhello@example.com'))

The example code below will return myemailaddress .

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

const userEmail = 'myemailaddress@gmail.com';
getUsername(userEmail);

// Input: test.user@example.com. 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;
         }
      }

string.split(separator, limit) 是你想要的方法

"someone@example.com".split("@")[0]

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