javascript 38 lines · 8 steps

Parsing full names into first and last

A name splitter that handles whitespace, suffixes, comma order, and multi-word surname particles.

Explained by highlit
1function splitFullName(fullName) {
2 const cleaned = (fullName || '').trim().replace(/\s+/g, ' ');
3 
4 if (!cleaned) {
5 return { firstName: '', lastName: '' };
6 }
7 
8 const suffixes = /^(jr|sr|ii|iii|iv|md|phd|esq)\.?$/i;
9 const parts = cleaned.split(' ');
10 
11 let suffix = '';
12 if (parts.length > 2 && suffixes.test(parts[parts.length - 1])) {
13 suffix = parts.pop();
14 }
15 
16 if (parts.length === 1) {
17 return { firstName: parts[0], lastName: '', suffix };
18 }
19 
20 if (cleaned.includes(',')) {
21 const [last, rest] = cleaned.split(',', 2).map((s) => s.trim());
22 return { firstName: rest, lastName: last, suffix };
23 }
24 
25 const particles = /^(van|von|de|del|della|di|da|la|le|st\.?|mac|mc|o')$/i;
26 let splitIndex = parts.length - 1;
27 while (splitIndex > 1 && particles.test(parts[splitIndex - 1])) {
28 splitIndex -= 1;
29 }
30 
31 return {
32 firstName: parts.slice(0, splitIndex).join(' '),
33 lastName: parts.slice(splitIndex).join(' '),
34 suffix,
35 };
36}
37 
38export default splitFullName;
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing input first lets every later step assume clean, single-spaced text.
  2. 2Real-world names need special handling for suffixes, comma ordering, and surname particles like 'van' or 'de'.
  3. 3Returning a consistent object shape keeps callers simple no matter which branch runs.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing full names into first and last — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code