Get initials from a name in JavaScript
Beginner · 3 min read
Initials are everywhere in apps: the round avatar that shows CO when someone hasn't uploaded a photo, a signature line, a short label on a chat message. Turning Chinwe Adaeze Okonkwo into C.A.O. is a small, satisfying exercise that teaches three array tools you'll use every day.
In this tutorial you will write a function called initials that copes with lowercase input, extra spaces and empty input, and lets you decide what a hyphenated surname like Ade-Bello should do. You should know what strings, arrays and functions are.
The plan
To get initials from a name:
- Split the name into words.
- Take the first letter of each word and make it uppercase.
- Join the letters back together, with a dot after each.
map: change every item in an array
map runs a small function on every item in an array and gives you a new array of the results. The original array is left alone.
const words = ['bola', 'ahmed'];
console.log(words.map((w) => w.toUpperCase())); // [ 'BOLA', 'AHMED' ]
(w) => w.toUpperCase() is an arrow function: a short way to write a function. Here it takes one word, w, and returns it in capitals. w[0] reads the first character of a word.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
106 Initials from a name
easyTurn Chinwe Adaeze Okonkwo into C.A.O. Handle lowercase input, extra spaces, an empty string, and decide what a hyphenated surname should do.
Stuck? Three hints, smallest first
- 1. Split into words, take the first character of each, uppercase it.
- 2. Filter out empty words or you will get a stray separator.
- 3. Whether
Ade-Bellois one initial or two is a decision, not a bug — make it visible.
Step 1: first letters
const words = 'Chinwe Adaeze Okonkwo'.split(' ');
const letters = words.map((w) => w[0].toUpperCase() + '.');
console.log(letters); // [ 'C.', 'A.', 'O.' ]
console.log(letters.join('')); // C.A.O.
map turns each word into its first letter plus a dot. join('') glues them with nothing in between.
Step 2: the stray space that crashes it
Try the same code on a name typed with a space in front:
const words = ' Bola Ahmed'.split(' ');
console.log(words); // [ '', 'Bola', 'Ahmed' ]
try {
words.map((w) => w[0].toUpperCase());
} catch (err) {
console.log(err.name); // TypeError
}
The first word is an empty string. ''[0] is undefined, and undefined.toUpperCase() throws a TypeError. The code works on tidy test names and crashes on the input real users type.
Step 3: clean the words first
const words = ' Bola Ahmed '.trim().split(/\s+/).filter(Boolean);
console.log(words); // [ 'Bola', 'Ahmed' ]
trim() removes the spaces at the ends. split(/\s+/) splits on any run of whitespace, so three spaces count as one gap. filter(Boolean) keeps only the items that count as true, which throws away any empty strings that are left. Now every word has a first letter.
Step 4: the function
function initials(name, separator = '.', splitOn = /\s+/) {
const words = String(name).trim().split(splitOn).filter(Boolean);
return words.map((w) => w[0].toUpperCase() + separator).join('');
}
console.log(initials('Chinwe Adaeze Okonkwo')); // C.A.O.
console.log(initials('bola ahmed')); // B.A.
console.log(initials(' ') === ''); // true
console.log(initials('Chinwe Adaeze Okonkwo', '')); // CAO
The two extra parameters have default values: if you don't pass them, separator is '.' and splitOn is /\s+/. Passing '' as the separator gives the compact form you'd put in an avatar.
An empty name gives an empty array of words, and joining an empty array gives ''. No crash, and no lone dot.
Step 5: decide about hyphens
Is Ngozi Ade-Bello two initials or three? Splitting on whitespace treats Ade-Bello as one word. The pattern /[\s-]+/ means "one or more spaces or hyphens", so it splits there too:
function initials(name, separator = '.', splitOn = /\s+/) {
const words = String(name).trim().split(splitOn).filter(Boolean);
return words.map((w) => w[0].toUpperCase() + separator).join('');
}
const withHyphens = (name) => initials(name, '.', /[\s-]+/);
console.log(initials('Ngozi Ade-Bello')); // N.A.
console.log(withHyphens('Ngozi Ade-Bello')); // N.A.B.
Neither answer is wrong. It's a choice about your product. Making the pattern a parameter means the choice is written down where anyone reading the code can see it.
The full solution
The answer panel has initials and withHyphens, and checks lowercase input, one name, extra spaces, an empty name, both hyphen choices and the compact form. Press Run to see the output.
function initials(name, separator = '.', splitOn = /\s+/) {
const words = String(name).trim().split(splitOn).filter(Boolean);
return words.map((w) => w[0].toUpperCase() + separator).join('');
}
const withHyphens = (name) => initials(name, '.', /[\s-]+/);
console.log(initials('Chinwe Adaeze Okonkwo'), '|', initials('ngozi ade-bello'), '|', withHyphens('ngozi ade-bello'));
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three names, three initials', initials('Chinwe Adaeze Okonkwo'), 'C.A.O.');
test('lowercase input is raised', initials('bola ahmed'), 'B.A.');
test('one name gives one initial', initials('Ngozi'), 'N.');
test('extra whitespace does not add empty initials', initials(' Bola Ahmed '), 'B.A.');
test('empty input gives empty text, not a lone dot', initials(' '), '');
test('to whitespace, a hyphenated surname is one word', initials('Ngozi Ade-Bello'), 'N.A.');
test('treat the hyphen as a separator and it is two', withHyphens('Ngozi Ade-Bello'), 'N.A.B.');
test('the separator is a parameter, so a compact form is free', initials('Chinwe Adaeze Okonkwo', ''), 'CAO');
filter(Boolean) is doing real work. Without it a leading space produces an empty word, w[0] on it is undefined, and undefined.toUpperCase() throws — so the crash appears only for input with a stray space, which is exactly the input a user provides. Trimming and filtering together make the empty case return '' instead of a lone separator.
The hyphen is the interesting part, and it is a product question rather than a coding one. Splitting on whitespace gives Ngozi Ade-Bello two initials; splitting on whitespace or hyphens gives three. Both are defensible; what is not defensible is discovering which one you chose from a bug report. Passing the pattern in makes the choice a visible argument. Same ground as exercise 24, which capitalised every word — there the first letter was changed in place, here it is all that survives.
Common mistakes
- Leaving out
filter(Boolean). One empty word andw[0].toUpperCase()throws. - Forgetting
toUpperCase().'bola ahmed'would give'b.a.'. - Using
join()with no argument. It puts commas between the items:'C.,A.,O.'.
Try it yourself
- Make an avatar version that returns at most two letters:
'CO'for'Chinwe Adaeze Okonkwo', using the first and last word. - Call
initialswith' 'as the separator. What do you get, and is there a trailing space? - What does
initials('émeka obi')give? DoestoUpperCasehandle the accent?