How can I extract the user name from an email address using javascript?
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
How to retrieve Name from Email Address
var email = "john.doe@example.com";
var name = email.substring(0, email.lastIndexOf("@"));
var domain = email.substring(email.lastIndexOf("@") +1);
console.log( name ); // john.doe
console.log( domain ); // example.com
The above will also work for valid names containing @
(tools.ietf.org/html/rfc3696Page 5):
john@doe
"john@@".doe
"j@hn".d@e
- String.prototype.substring()
- String.prototype.lastIndexOf()
Given the email value is already validated, String.prototype.match() can be than used to retrieve the desired name, domain:
String match:
const name = email.match(/^.+(?=@)/)[0];
const domain = email.match(/(?<=.+@)[^@]+$/)[0];
Capturing Group:
const name = email.match(/(.+)@/)[1];
const domain = email.match(/.+@(.+)/)[1];
To get both fragments in an Array, use String.prototype.split() to split the string at the last @
character:
const [name, domain] = email.split(/(?<=^.+)@(?=[^@]+$)/);
console.log(name, domain);
or simply with /@(?=[^@]*$)/
.
Here's an example that uses a reusable function getEmailFragments( String )
const getEmailFragments = (email) => email.split(/@(?=[^@]*$)/);
[ // LIST OF VALID EMAILS:
`info@example.com`,
`john@doe@example.com`,
`"john@@".doe@example.com`,
`"j@hn".d@e@example.com`,
]
.forEach(email => {
const [name, domain] = getEmailFragments(email);
console.log("DOMAIN: %s NAME: %s ", domain, name);
});
extract first and last name from pattern email address
Use String.prototype.split()
method:
var empmail = 'charles.x.markus.bukowski@company.com'
var fullName = empmail.split('@')[0].split('.');
var firstName = fullName[0];
var lastName = fullName[ fullName.length-1 ]
regex to match the string and extract email and user name in javascript
After carving out the valid JSON portion from the string you can parse it and access the properties you need:
const resp=`{
"typ": "JWT",
"alg": "44555"
}
{
"XForwardedFor": "12.134.234.22",
"sm_AppId": "test",
"UserId": "changu",
"sm_Userdn": "some userdn",
"Mail": "changu@gmail.com",
"DomainName": "www.test.com",
"UserAgent": "Amazon",
"CreationTime": "2020-09-08T05:01:55.616Z"
}
ii( NJm)'d=IXp:$uG\mf }`
let obj=JSON.parse(resp.match(/\{[^{]*UserId[^}]*\}/))
console.log(obj.UserId, obj.Mail)
Extract name and email from string in JS
It's hard to tell if the data will change or remain the same, but here's my attempt:
var re = /(?:"?([A-Z][^<"]+)"?\s*)?<?([^>\s,]+)/g;
while (m = re.exec(str)) {
if(m[1]) { m[1] = m[1].trim() }
console.log("Name: " + m[1]);
console.log("Email: " + m[2]);
}
Working Demo
Extract email address from Google account
Here is a way to receive data (email, etc.) in JavaScript. At the end it shows an alert with data. (You can store this data in a database.) It's a complete working example with a Google button.
<html>
<head>
<title>Demo: Getting an email address using the Google+ Sign-in button</title>
<!-- Include the API client and Google+ client. -->
<script src = "https://plus.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<!-- Container with the Sign-In button. -->
<div id="gConnect" class="button">
<button class="g-signin"
data-scope="email"
data-clientid="Your_Client_ID"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
<!-- Textarea for outputting data -->
<div id="response" class="hide">
<textarea id="responseContainer" style="width:100%; height:150px"></textarea>
</div>
</div>
</body>
<script>
/**
* Handler for the signin callback triggered after the user selects an account.
*/
function onSignInCallback(resp) {
gapi.client.load('plus', 'v1', apiClientLoaded);
}
/**
* Sets up an API call after the Google API client loads.
*/
function apiClientLoaded() {
gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
}
/**
* Response callback for when the API client receives a response.
*
* @param resp The API response object with the user email and profile information.
*/
function handleEmailResponse(resp) {
var primaryEmail;
var name;
var gender;
for (var i=0; i < resp.emails.length; i++) {
if (resp.emails[i].type === 'account')
primaryEmail = resp.emails[i].value;
if (resp.displayName != null)
name = resp.displayName;
gender = resp.gender;
}
document.getElementById('responseContainer').value = 'Primary email: ' +
primaryEmail + '\n\nFull Response:\n' + JSON.stringify(resp);
ShowAlert("Email: "+primaryEmail +" "+"Name: "+ resp.displayName +" "+"Gender: "+gender);
}
</script>
</html>
For further information and detail you can (should) read this link:
Getting people and profile information
Using regex to extract username from email address
The regular expression that will match and capture any character until it reaches the @
character:
([^@]+)
That seems like what you need. It'll handle all kinds of freaky variations on e-mail addresses.
I'm not sure why Ben James deleted his answer, since I feel it's better than mine. I'm going to post it here (unless he undeletes his answer):
Why use regex instead of string functions?
$parts = explode("@", "johndoe@domain.com");
$username = $parts[0];
You don't need regular expressions in this situation at all. I think using explode
is a much better option, personally.
As Johannes Rössel points out in the comments, e-mail address parsing is rather complicated. If you want to be 100% sure that you will be able to handle any technically-valid e-mail address, you're going to have to write a routine that will handle quoting properly, because both solutions listed in my answer will choke on addresses like "a@b"@example.com
. There may be a library that handles this kind of parsing for you, but I am unaware of it.
Related Topics
Hiding the Address Bar of a Browser (Popup)
Regex to Get String Between Curly Braces
Display Current Date in Dd/Mm/Yyyy Format
Group By, and Sum, and Generate an Object for Each Array in JavaScript
Split a String Only the At the First N Occurrences of a Delimiter
Creating a Leaderboard in Html/Js
How to Read a Properties File in JavaScript from Project Directory
How to Trigger Change of Option in Dropdown When Options Can Have Same Value
How to Open a Url Link from JavaScript Inside a Google Apps Script HTML Google Site Gadget
How to Share and Edit Global Variables Between Two JavaScript Node Runs
Passing Variable from One Js to Another Js File in Nodejs
How to Force Clients to Refresh JavaScript Files
Draw a Connecting Line Between Two Elements
Javascript on Click Event for Multiple Buttons With Same Class
How to Find Previous or Next Element from Array in JavaScript
Regex in JavaScript Allow Only Numbers and One Dot Followed by Max 2 Number