Create a Username From an Email in JavaScript

Quick Summary
- Suggest a username by taking the part of an email address before the @ and removing everything except letters and digits.
- On submit, a jQuery handler builds the username, turning john.doe+news@example.com into johndoenews, and writes it into the p_name field.
- The sample form lacks a p_name field, so add one, and validate the email and check username availability on the server.
When a sign-up form asks for an email address, you can suggest a username from it: take the part before the @ and keep only letters and numbers. This JavaScript and jQuery example shows the idea with a simple form.
The HTML form
A basic form with an email field and a submit button. The IDs test and email are what the script looks for.
<form action="#" method="post" id="test">
<label for="email">E-mail
<input type="text" name="email" id="email" />
</label>
<input type="submit" name="submit" value="Create username"/>
</form>The JavaScript that creates a username from the email
var createUserName = function(value) {
var parts = value.split('@');
var user = parts[0];
var username = user.replace(/[^a-z\d]+/ig, '');
return username;
};
$('#test').submit(function(e) {
e.preventDefault();
var $value = $('#email').val();
var $username = createUserName($value);
document.getElementById('p_name').value = $username;
alert($username);
});createUserName()splits the address at@, keeps the first part and removes every character that isn’t a letter or a digit. For example,john.doe+news@example.combecomesjohndoenews. Uppercase letters are kept, because the pattern uses theiflag.- On submit, the handler stops the form from being sent, builds the username, writes it into the field with the ID
p_nameand shows it in an alert.
The sample form has no p_name field. Add one, for example the username input of your real form; otherwise the script stops with an error before the alert appears. Remove the alert() once everything works.
The script needs jQuery loaded before it. It doesn’t check that the email address is valid or that the username is still free, so do those checks on the server when you create the account.
Related articles
- checking that two password fields match as the user types: another small helper for the same sign-up form
- reading an input’s value in plain JavaScript: the same first step without jQuery
See also: How to Add USA States to a Dropdown With JavaScript.
