splitFullName(name) turns a full name into [first, last]. It trims extra spaces, keeps particles like van, de, von, da, del, and la with the last name, and leaves a single-word name as the first name with an empty last name.
When to use
- Splitting a "Full name" column into First and Last before a mail merge
- Cleaning a form response or imported list of names
- Any script that needs a last name without dropping "van" or "de la"
How to use this snippet
/**
* Split a full name into [first, last]. Extra spaces are trimmed. Particles
* van, de, von, da, del, and la stay with the last name (matched
* case-insensitively, original spelling kept). A single-word name is
* returned as [name, '']. Everything before the last-name group is first,
* so a middle name stays with first.
*
* @param {string} name
* @return {string[]}
*/
function splitFullName(name) {
var particles = { van: 1, de: 1, von: 1, da: 1, del: 1, la: 1 };
var s = String(name == null ? '' : name).trim().replace(/\s+/g, ' ');
if (!s) return ['', ''];
var parts = s.split(' ');
if (parts.length === 1) return [parts[0], ''];
var last = [parts.pop()];
while (parts.length) {
var prev = parts[parts.length - 1];
if (particles[String(prev).toLowerCase()]) {
last.unshift(parts.pop());
} else {
break;
}
}
if (!parts.length) return ['', last.join(' ')];
return [parts.join(' '), last.join(' ')];
}
Example
function splitNameColumn() {
var sheet = SpreadsheetApp.getActive().getSheetByName('People');
var last = sheet.getLastRow();
if (last < 2) return;
var names = sheet.getRange(2, 1, last - 1, 1).getValues();
var out = names.map(function (r) { return splitFullName(r[0]); });
sheet.getRange(2, 2, out.length, 2).setValues(out); // B first, C last
}
Notes
"Vincent van Gogh"becomes["Vincent", "van Gogh"]."Maria de la Cruz"becomes["Maria", "de la Cruz"]."Madonna"becomes["Madonna", ""]."Mary Ann Smith"becomes["Mary Ann", "Smith"]— the helper does not try to guess middle names versus double first names.- Particles not in that list (for example
derin "van der Waals") stay with the first name. Add them to theparticlesobject in the function if you need them. - Suffixes like Jr or III are not special-cased; they will be treated as the last name.
Happy Coding!
