Alphabetize a string's letters with regex in JavaScript
Beginner · 3 min read
Sorting the letters of a word is a small trick with real uses. Two words are anagrams when their sorted letters match, word games use it to look up answers, and it is a classic warm-up question in interviews. This exercise asks for one specific result: 'United States' should become 'SUadeeinsttt'.
That result looks odd at first. Why do S and U come before a? By the end of this tutorial you will know, and you will also have a vowel counter, since the exercise asks for that too. You need to know what arrays and join are. Regex parts are explained as we go.
Turning a string into letters
[...text] spreads a string into an array with one character per item. Arrays can be sorted, and join('') glues them back into a string:
console.log([...'bus']); // [ 'b', 'u', 's' ]
console.log([...'bus'].sort().join('')); // 'bsu'
How sort() orders letters
With no arguments, sort() compares characters by their code, the number the computer stores for each one. You can see the code with charCodeAt:
console.log('A'.charCodeAt(0)); // 65
console.log('S'.charCodeAt(0)); // 83
console.log('a'.charCodeAt(0)); // 97
Every capital letter (65 to 90) has a smaller code than every lower-case letter (97 to 122). So all capitals sort first. That is the whole mystery of 'SUadeeinsttt'.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
8 Count vowels, and sort a string’s letters
easyThe title asks for a vowel count; the test data shows alphabetize_string('United States') giving "SUadeeinsttt". Both are done here.
Stuck? Three hints, smallest first
- 1. For counting:
match(/[aeiou]/gi)and remember it returnsnull, not[]. - 2. For sorting: spread into characters,
sort(), join back. - 3. Default
sort()compares by code unit, so every capital comes before every lower-case letter.
Step 1: sort the letters
Spread, sort, join:
const sortChars = (text) => [...text].sort().join('');
console.log(JSON.stringify(sortChars('United States'))); // " SUadeeinsttt"
Close, but there is a space at the front. A space has code 32, smaller than any letter, so it sorts first.
Step 2: remove whitespace first
\s matches any whitespace character, and the g flag replaces every one of them, not just the first. Replacing with '' removes them:
const alphabetizeString = (text) => [...text.replace(/\s/g, '')].sort().join('');
console.log(alphabetizeString('United States')); // 'SUadeeinsttt'
console.log(alphabetizeString('United States').length); // 12
That matches the expected output exactly. Twelve letters: the original 13 characters minus the space.
Step 3: sort the human way
If you want a and A next to each other, give sort a compare function. localeCompare compares letters the way a dictionary does. Pass a locale such as 'en' so the result is the same on every machine:
console.log([...'bAaB'].sort().join('')); // 'ABab'
console.log([...'bAaB'].sort((x, y) => x.localeCompare(y, 'en')).join('')); // 'aAbB'
The exercise wants the first result, so the answer keeps the plain sort().
Step 4: count the vowels
Now the other half. [aeiou] is a character class: any one of those five letters. The i flag ignores case, and g finds every match. match then returns an array of everything it found:
console.log('United States'.match(/[aeiou]/gi)); // [ 'U', 'i', 'e', 'a', 'e' ]
Count the array and you have the vowels. But watch what happens with a word that has none:
console.log('rhythm'.match(/[aeiou]/gi)); // null
match returns null, not an empty array, when nothing is found. Asking for null.length throws an error.
Step 5: handle the empty case
?? [] means "if the left side is null or undefined, use an empty array instead":
const countVowels = (text) => (text.match(/[aeiou]/gi) ?? []).length;
console.log(countVowels('United States')); // 5
console.log(countVowels('AEIOU')); // 5
console.log(countVowels('rhythm')); // 0
console.log(countVowels('')); // 0
The letter y is not counted here, since it is not in the class.
The full solution
The panel has both functions, plus a breakdown that counts each vowel separately. Press Run to see 'SUadeeinsttt' appear and the character codes that explain it.
// What the TITLE asks for.
const countVowels = (text) => (text.match(/[aeiou]/gi) ?? []).length;
// What the TEST DATA asks for. Whitespace removed, then sorted.
const alphabetizeString = (text) => [...text.replace(/\s/g, '')].sort().join('');
// A breakdown, since "count the vowels" usually leads to "which ones".
function vowelBreakdown(text) {
const found = text.toLowerCase().match(/[aeiou]/g) ?? [];
const counts = {};
for (const v of found) counts[v] = (counts[v] ?? 0) + 1;
return counts;
}
console.log("countVowels('United States') =", countVowels('United States'));
console.log("alphabetizeString('United States') =", JSON.stringify(alphabetizeString('United States')));
console.log("the expected value =", JSON.stringify('SUadeeinsttt'));
console.log('breakdown:', vowelBreakdown('United States'));
console.log('--- why capitals sort first ---');
console.log("'S'.charCodeAt(0) =", 'S'.charCodeAt(0), " 'a'.charCodeAt(0) =", 'a'.charCodeAt(0));
console.log("sorted by code unit:", JSON.stringify([...'bAaB'].sort().join('')));
console.log("sorted by locale :", JSON.stringify([...'bAaB'].sort((x, y) => x.localeCompare(y, 'en')).join('')));
Output
16 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the exact expected output", alphabetizeString('United States'), 'SUadeeinsttt');
test('the space is removed', alphabetizeString('United States').includes(' '), false);
test('the length matches the input minus the space', alphabetizeString('United States').length, 12);
test('vowels in "United States"', countVowels('United States'), 5);
test('counting is case-insensitive', countVowels('AEIOU'), 5);
test('and matches lower case too', countVowels('aeiou'), 5);
test('a string with no vowels counts 0', countVowels('rhythm'), 0);
test('rather than crashing on null', 'rhythm'.match(/[aeiou]/gi), null);
test('an empty string counts 0', countVowels(''), 0);
test('y is not counted as a vowel here', countVowels('y'), 0);
test('the breakdown adds up to the total', Object.values(vowelBreakdown('United States')).reduce((a, b) => a + b, 0), countVowels('United States'));
test('and names each vowel', vowelBreakdown('United States'), { u: 1, i: 1, e: 2, a: 1 });
test('capitals sort before lower case by code unit', [...'bAaB'].sort().join(''), 'ABab');
test('because S is 83 and a is 97', ['S'.charCodeAt(0), 'a'.charCodeAt(0)], [83, 97]);
test('a locale sort groups the cases instead', [...'bAaB'].sort((x, y) => x.localeCompare(y, 'en')).join(''), 'aAbB');
test('sorting is stable for repeated characters', alphabetizeString('aaa'), 'aaa');
The title and the test data ask for different things, so both are here: countVowels for the title, alphabetizeString for the data, and the assertion reproduces "SUadeeinsttt" exactly.
That output explains itself once you look at the code units. Default sort() compares strings by UTF-16 code unit, and every ASCII capital (65–90) comes before every lower-case letter (97–122) — so S and U lead, and the assertion checks 83 against 97. If you want aAbB instead, pass localeCompare with an explicit locale.
The ?? [] after match is the recurring detail: match with the g flag returns null when nothing matches, not an empty array, so .length on it throws. The assertion checks the null directly so the reason is visible.
Common mistakes
- Forgetting to remove the space. It sorts to the front, so you get
' SUadeeinsttt'with a leading space. - Expecting
sort()to ignore case. It sorts by character code, so capitals always come first. UselocaleComparewhen you want dictionary order. - Calling
.lengthstraight onmatch. For a word with no vowels it isnull, and the code crashes. Add?? [].
Try it yourself
- Use
alphabetizeStringto writeisAnagram(a, b). Lower-case both words first, so'Listen'and'Silent'match. - Count consonants instead of vowels. (Hint:
[b-df-hj-np-tv-z]with theiflag.) - Sort the letters in reverse order by adding
.reverse()beforejoin.