Emmanuel Akinfulubi

JavaScriptBasic

Split a full name into first and last name in JavaScript

Beginner · 3 min read

Sign-up forms often ask for a full name in one box, and later the app needs just the first name for "Hi, Chinwe" or the surname for a sorted list. Splitting the name sounds like one line of code. It turns into several once you meet real input: one name, four names, or someone who pressed the space bar twice.

In this tutorial you will write a function called nameParts that takes a full name and returns its first name, middle names and surname as an object. You should know what a string, an array and a function are. The rest is explained as we go.

Splitting a string into an array

split cuts a string wherever it finds a separator and gives you an array of the pieces:

JavaScript

console.log('Bola Ahmed'.split(' ')); // [ 'Bola', 'Ahmed' ]

The separator can also be a regular expression, a pattern written between slashes. /\s+/ means "one or more whitespace characters in a row": spaces, tabs or newlines. You'll see in a moment why that matters.

Taking an array apart

Destructuring pulls items out of an array into variables. The ...rest part collects everything left over into a new array:

JavaScript

const [first, ...rest] = ['Chinwe', 'Adaeze', 'Okonkwo'];
console.log(first); // Chinwe
console.log(rest);  // [ 'Adaeze', 'Okonkwo' ]

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

105 Split a full name into its parts

easy

Take a full name as typed and pull out the first name, any middle names and the surname. Cope with one name only, with two, with three, with four, and with someone who leaned on the space bar.

Stuck? Three hints, smallest first
  1. 1. Trim first, then split on /\s+/ so a double space does not become an empty name.
  2. 2. The surname is the last part — but only if there is more than one part.
  3. 3. Everything between the first and last belongs to the middle, however many there are.

Step 1: the obvious split, and where it breaks

Splitting on a single space works until someone types two:

Step 1

console.log('Bola  Ahmed'.split(' ')); // [ 'Bola', '', 'Ahmed' ]

Between the two spaces there is nothing, so split(' ') gives an empty string as a piece. Take the last piece as the surname and you're fine here, but with 'Bola Ahmed ' (spaces at the end) the surname would be ''.

Step 2: split on any run of whitespace

Step 2

console.log('Bola  Ahmed'.split(/\s+/));       // [ 'Bola', 'Ahmed' ]
console.log('  Bola Ahmed'.split(/\s+/));      // [ '', 'Bola', 'Ahmed' ]
console.log('  Bola Ahmed'.trim().split(/\s+/)); // [ 'Bola', 'Ahmed' ]

/\s+/ treats two spaces, or a tab, as one separator. Leading spaces still make an empty first piece, so trim() comes first. As a final safety net, .filter(Boolean) drops any empty strings that are left, because an empty string counts as false.

Step 3: first, middle and last

Now take the cleaned list apart:

Step 3

const parts = ['Ifeoma', 'Ada', 'Ugochi', 'Nwosu'];
const [first, ...rest] = parts;
const last = rest.length ? rest[rest.length - 1] : '';
const middle = rest.slice(0, -1).join(' ');
console.log(first);  // Ifeoma
console.log(middle); // Ada Ugochi
console.log(last);   // Nwosu

The first piece is the first name. The surname is the last item of rest, but only if rest has anything in it. Otherwise the person typed one name, and that's a first name, not a surname.

rest.slice(0, -1) is everything in rest except its last item, and join(' ') turns those back into one string. That way two middle names, or five, stay together.

Step 4: put it in a function

Step 4

function nameParts(full) {
  const parts = String(full).trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return { first: '', middle: '', last: '' };
  const [first, ...rest] = parts;
  const last = rest.length ? rest[rest.length - 1] : '';
  const middle = rest.slice(0, -1).join(' ');
  return { first, middle, last };
}
console.log(nameParts('Chinwe Adaeze Okonkwo')); // { first: 'Chinwe', middle: 'Adaeze', last: 'Okonkwo' }
console.log(nameParts('Ngozi'));                 // { first: 'Ngozi', middle: '', last: '' }
console.log(nameParts('   '));                   // { first: '', middle: '', last: '' }

String(full) makes sure the function works even if it is handed something other than a string. The if handles a box with nothing in it: without it, first would be undefined. { first, middle, last } is shorthand for { first: first, middle: middle, last: last }.

A word about real names

"First, middle, last" is one naming custom, not a rule. Some people have a single name, some put the family name first, and some surnames contain a space, like de Souza. No splitting trick gets all of those right. If your app really needs a surname, the safest choice is to ask for it in its own field.

The full solution

The answer panel has the finished nameParts and tests it on two, three and four names, a single name, extra spaces with a tab, and an empty box. It also shows the single-space split going wrong. Press Run to see the output.

The answer

function nameParts(full) {
  const parts = String(full).trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return { first: '', middle: '', last: '' };
  const [first, ...rest] = parts;
  const last = rest.length ? rest[rest.length - 1] : '';
  const middle = rest.slice(0, -1).join(' ');
  return { first, middle, last };
}
console.log(nameParts('Chinwe Adaeze Okonkwo'));
console.log('a double space, split on a single one:', JSON.stringify('Bola  Ahmed'.split(' ')));

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.

8 checks

test('three names split into three roles', nameParts('Chinwe Adaeze Okonkwo'), { first: 'Chinwe', middle: 'Adaeze', last: 'Okonkwo' });
test('two names leave the middle empty', nameParts('Bola Ahmed'), { first: 'Bola', middle: '', last: 'Ahmed' });
test('one name is a first name, not a surname', nameParts('Ngozi'), { first: 'Ngozi', middle: '', last: '' });
test('several middle names stay together', nameParts('Ifeoma Ada Ugochi Nwosu').middle, 'Ada Ugochi');
test('extra spaces and a stray tab do not become empty parts', nameParts('  Bola\t  Ahmed  '), { first: 'Bola', middle: '', last: 'Ahmed' });
test('empty input gives empty parts rather than throwing', nameParts('   '), { first: '', middle: '', last: '' });
test('splitting on a single space would have made an empty name', 'Bola  Ahmed'.split(' '), ['Bola', '', 'Ahmed']);
test('which /\\s+/ avoids', 'Bola  Ahmed'.split(/\s+/), ['Bola', 'Ahmed']);

split(' ') is the trap: it splits on exactly one space, so 'Bola Ahmed' becomes three parts with an empty string in the middle, and the surname ends up being ''. split(/\s+/) treats any run of whitespace as one separator and handles the tab a paste brings with it. The trim matters too — a leading space would still produce an empty first element even with the regex.

The design point is bigger than the code. "First, middle, last" is a Western convention, not a fact: many people have one name, many surnames come first, and plenty contain spaces (de Souza, Ade Bello). This function will get those wrong, and no clever splitting fixes it. If the name matters, ask for the parts you need in separate fields and store what you were given; parse only when you have no choice, as here.

Common mistakes

  • Splitting on ' '. Two spaces in a row make an empty name. Use /\s+/.
  • Skipping trim(). A leading space gives an empty first piece even with the regular expression.
  • Calling a lone name a surname. With one word, rest is empty, so the surname must be ''.

Try it yourself

  1. Write greeting(full) that returns 'Hi, Chinwe' using nameParts.
  2. Write sortName(full) that returns 'Okonkwo, Chinwe', or just the first name if there is no surname.
  3. Change nameParts so it also returns count, the number of names it found.

Keep practising

Newsletter

New writing, when it lands.

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