Emmanuel Akinfulubi

JavaScriptString

Extract initials from a name string in JavaScript

Intermediate · 3 min read

Chat apps, email clients and dashboards often show a little circle with your initials when you have no profile picture: AL for Ada Lovelace. Getting initials from a name looks like a one-liner, and it nearly is. The interesting part is what happens with messy input: extra spaces, an empty name field, or a name that starts with an emoji.

In this tutorial you will build initials step by step, see exactly where it would crash, and finish with a version that keeps emoji whole. You should know trim, split, map and join. Regex and filter(Boolean) are explained below.

The plan

  1. trim() the name, so spaces at the ends don't count.
  2. split it into words on any run of whitespace.
  3. Take the first character of each word and uppercase it.
  4. join('') the letters together.

Splitting on any whitespace

split(' ') splits on exactly one space, so two spaces in a row produce an empty word between them. split(/\s+/) uses a regex instead: \s means any whitespace character (space, tab, newline) and + means "one or more", so a whole run of spaces counts as one gap.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

49 Initials from a name

fair

Turn 'Ada Lovelace' into 'AL'. Handle extra whitespace, an empty name, and a name whose first character is an emoji.

Stuck? Three hints, smallest first
  1. 1. Trim, split on whitespace, take the first character of each part.
  2. 2. Splitting an empty string gives one empty part, and indexing that gives undefined.
  3. 3. word[0] takes one code unit, so spread the word if it might start with an emoji.

Step 1: split the name into words

Step 1

console.log('Ada Lovelace'.split(/\s+/));              // [ 'Ada', 'Lovelace' ]
console.log('  ada   lovelace  '.trim().split(/\s+/)); // [ 'ada', 'lovelace' ]

Without trim(), the leading spaces would become an empty first word. Trimming first means the split only sees the gaps between words.

Step 2: first letter of each word

Step 2

const words = ['ada', 'lovelace'];
console.log(words.map((w) => w[0].toUpperCase()).join('')); // 'AL'

w[0] is the first character of each word. toUpperCase() makes it a capital, so a name typed in lowercase still gives AL. join('') glues the letters with nothing between them.

Step 3: the empty name, the natural wrong turn

An empty name field is the normal state of every form before someone types in it. Watch what splitting does to it:

Step 3

console.log(''.split(/\s+/)); // [ '' ]
const words = ''.split(/\s+/);
try {
  words.map((w) => w[0].toUpperCase());
} catch (error) {
  console.log(error.constructor.name); // 'TypeError'
}

Splitting an empty string doesn't give an empty array. It gives an array with one empty string in it. Then ''[0] is undefined, and calling toUpperCase() on undefined throws a TypeError. Your avatar code would crash on every new sign-up form.

Step 4: filter out empty words

Step 4

console.log([''].filter(Boolean));             // []
console.log(['ada', '', 'lovelace'].filter(Boolean)); // [ 'ada', 'lovelace' ]

filter(Boolean) keeps only items that are truthy, meaning they count as true in an if. An empty string is falsy, so it is dropped. Now an empty name gives an empty list of words, map has nothing to do, and the result is ''.

Step 5: the whole function

Step 5

const initials = (name) =>
  name.trim().split(/\s+/).filter(Boolean).map((w) => w[0].toUpperCase()).join('');
console.log(initials('Ada Lovelace'));             // 'AL'
console.log(initials('  ada   lovelace  '));       // 'AL'
console.log(initials('Chimamanda Ngozi Adichie')); // 'CNA'
console.log(JSON.stringify(initials('')));         // ""
console.log(initials('Ama Ata-Aidoo'));            // 'AA'
console.log(initials('Chimamanda Ngozi Adichie').slice(0, 2)); // 'CN'

A hyphenated surname counts as one word, because we only split on whitespace. If you want at most two letters, slice(0, 2) on the result is enough.

Step 6: names that start with an emoji

Some people put an emoji in their display name. Inside JavaScript, most emoji are stored as two pieces called code units, and w[0] takes only one of them:

Step 6

const initials = (name) =>
  name.trim().split(/\s+/).filter(Boolean).map((w) => w[0].toUpperCase()).join('');
console.log(initials('👍 ok')[0] === '👍'); // false
console.log(initials('👍 ok').length);      // 2

The result has a broken half-emoji as its first character, followed by O. On screen that half shows as a box or a question mark.

Step 7: take a whole character

Step 7

const initialsSafe = (name) =>
  name.trim().split(/\s+/).filter(Boolean).map((w) => [...w][0].toUpperCase()).join('');
console.log(initialsSafe('👍 ok'));        // '👍O'
console.log(initialsSafe('Ada Lovelace')); // 'AL'

[...w] spreads the word into an array of whole characters (code points), so [...w][0] is the full emoji. Ordinary names give the same result as before.

The full solution

The panel has both versions and prints five names, including the emoji one done both ways. Press Run and compare the last two lines, then read the checks underneath.

The answer

const initials = (name) =>
  name.trim().split(/\s+/).filter(Boolean).map((w) => w[0].toUpperCase()).join('');

// [...w][0] takes a whole code point rather than one code unit.
const initialsSafe = (name) =>
  name.trim().split(/\s+/).filter(Boolean).map((w) => [...w][0].toUpperCase()).join('');

console.log("'Ada Lovelace'              ->", initials('Ada Lovelace'));
console.log("'  ada   lovelace  '        ->", initials('  ada   lovelace  '));
console.log("'Chimamanda Ngozi Adichie'  ->", initials('Chimamanda Ngozi Adichie'));
console.log("'👍 ok', unsafe             ->", JSON.stringify(initials('👍 ok')), '<- half a character');
console.log("'👍 ok', safe               ->", initialsSafe('👍 ok'));

Output


      
10 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 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('two names give two letters', initials('Ada Lovelace'), 'AL');
test('extra whitespace is ignored', initials('  ada   lovelace  '), 'AL');
test('three names give three', initials('Chimamanda Ngozi Adichie'), 'CNA');
test('an empty name gives an empty string rather than throwing', initials(''), '');
test('the filter is what prevents that, because splitting "" gives one empty field', ''.split(/\s+/), ['']);
test('a hyphenated surname counts as one word', initials('Ama Ata-Aidoo'), 'AA');
test('splitting on the hyphen too would give three', 'Ama Ata-Aidoo'.split(/[\s-]+/).map((w) => w[0]).join(''), 'AAA');
test('capping at two is a slice, not a different algorithm', initials('Chimamanda Ngozi Adichie').slice(0, 2), 'CN');
test('w[0] takes half an astral character', initials('👍 ok')[0] === '👍', false);
test('spreading the word first fixes it', initialsSafe('👍 ok'), '👍O');

filter(Boolean) is the load-bearing line. Without it, initials('') reaches ''[0].toUpperCase() and throws a TypeError — and an empty name field is not an exotic input, it is the default state of every form.

Names are the classic example of data that resists rules. 'Ata-Aidoo', 'van der Berg', 'O'Brien' and mononyms all have a defensible answer that this function gets wrong. Where initials are shown to the person they belong to, let them be edited.

Common mistakes

  • Leaving out filter(Boolean). An empty name crashes with a TypeError. Filter out empty words before using w[0].
  • Splitting on a single space. split(' ') turns double spaces into empty words. Use /\s+/ after trim().
  • Using w[0] on names with emoji. It returns half a character. Use [...w][0].

Try it yourself

  1. Change initials to split on hyphens too, so 'Ama Ata-Aidoo' gives 'AAA'.
  2. Write avatarText(name) that returns at most two letters and '?' for an empty name.
  3. Make initials('van der Berg') return 'VB' by skipping a short list of small words.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.