String Mastery: Validate and Format Usernames in JavaScript
• Updated 6/18/2026 • JavaScriptStringsPattern MatchingBeginnerCoding Challenge
What You Will Build
In this JavaScript coding challenge, you will build a function called cleanUsernames(usernames). The function receives an array of raw username strings, cleans each value, validates it against clear username rules, and returns a new array containing only valid usernames.
This challenge helps you practice practical string manipulation, array processing, and regular expression validation.
Concept Overview
Strings are one of the most common data types in JavaScript. Usernames, emails, search terms, form inputs, and labels are all usually handled as strings.
JavaScript provides helpful string methods for cleaning and transforming text:
trim()removes leading and trailing whitespace.toLowerCase()converts letters to lowercase.replace()can replace text patterns.slice()can extract part of a string.
Regular expressions, often called regex, allow you to check whether a string matches a specific pattern. In this challenge, you will use regex to make sure each username contains only allowed characters and has a valid length.
Example
Given this input:
const usernames = [" alice_123 ", "Bob!", "charlie-99", "dave", "xy", "VeryLongUsername123"];
The function should clean and validate each username:
" alice_123 "becomes"alice_123"and is valid."Bob!"becomes"bob!"but is invalid because!is not allowed."charlie-99"is valid."dave"is valid."xy"is invalid because it is shorter than 3 characters."VeryLongUsername123"becomes lowercase but is invalid because it is longer than 15 characters.
Expected result:
["alice_123", "charlie-99", "dave"]
Coding Challenge
Write a function cleanUsernames(usernames) that accepts an array of strings and returns a new array of cleaned, valid usernames.
The original input array should not be modified. Invalid usernames should be skipped.
Requirements / Input‑Output Expectations
Constraints
usernames: an array of strings.- Each string may include uppercase letters, lowercase letters, numbers, symbols, or extra whitespace.
Hints
- Return a new array containing only valid usernames.
- Each returned username must be trimmed and converted to lowercase.
- The order of valid usernames must match their original order.
- Invalid usernames must not appear in the result.
Solution Walkthrough
- The input array can be empty.
- Each username must be between 3 and 15 characters after trimming.
- Allowed characters are lowercase letters
a-z, numbers0-9, underscores_, and hyphens-. - Usernames must be converted to lowercase before validation.
- Do not mutate the original input array.
Starter Code
- Create an empty result array.
- Loop through each raw username using
for...of. - Use
trim()to remove extra whitespace. - Use
toLowerCase()to normalize the username. - Use the regex
/^[a-z0-9_-]{3,15}$/to validate the cleaned username. - If the username is valid, add it to the result array.
Solution
The solution processes each username one at a time.
- Start with an empty array called
result. - For every username in the input array, remove extra whitespace using
trim(). - Convert the cleaned value to lowercase using
toLowerCase(). - Use a regular expression to check that the username contains only allowed characters and has the correct length.
- If the username passes validation, push it into
result. - Return
resultafter all usernames have been checked.
This approach is beginner-friendly because each step is clear and easy to debug.
Stretch Goals
/**
* Clean and validate an array of usernames.
*
* @param {string[]} usernames - The raw usernames to process.
* @returns {string[]} A new array of cleaned, valid usernames.
*/
function cleanUsernames(usernames) {
// TODO: Create a result array
// TODO: Loop through usernames
// TODO: Trim and lowercase each username
// TODO: Validate using a regular expression
// TODO: Return the result array
}
const input = [" alice_123 ", "Bob!", "charlie-99", "dave", "xy"];
console.log(cleanUsernames(input));
// Expected output: ["alice_123", "charlie-99", "dave"]
Solution
function cleanUsernames(usernames) {
const result = [];
const validUsernamePattern = /^[a-z0-9_-]{3,15}$/;
for (const rawUsername of usernames) {
const cleanedUsername = rawUsername.trim().toLowerCase();
if (validUsernamePattern.test(cleanedUsername)) {
result.push(cleanedUsername);
}
}
return result;
}
Alternative Solution Using filter() and map()
function cleanUsernames(usernames) {
const validUsernamePattern = /^[a-z0-9_-]{3,15}$/;
return usernames
.map((username) => username.trim().toLowerCase())
.filter((username) => validUsernamePattern.test(username));
}
Stretch Goals
- Return an object with two arrays:
validandinvalid. - For each invalid username, include a reason such as
too_short,too_long, orinvalid_characters. - Allow periods
.in usernames, but not at the beginning or end. - Prevent usernames from starting with a number.
- Build a small web form where users can enter usernames and see which ones pass validation.

