JSFiddle - React, Tailwind, and code Playground
by Ian Sanders
HTML
<form>
<input type='text' id='fullName'>
<input type='button' onClick='makeSortName()'>
</form>
Open the console to see outputted names.
JavaScript
function stripName(name) {
return name.replace(/\./g,'').toLowerCase();
}
function makeSortName() {
var fullName = document.getElementById('fullName').value.replace(/\,/g,'').split(' '),
//Remove commas and split into array
articles = ['a', 'an', 'the', 'los', 'las', 'el', 'la'],
titles = ['mr', 'mister', 'ms', 'miss', 'mz', 'mrs', 'missus', 'mx', 'sir', 'honorable', 'master', 'dr', 'doctor', 'lady', 'lord', 'madam', 'prof', 'professor', 'fr', 'father', 'rev', 'reverend', 'sr', 'sister', 'br', 'brother', 'pr', 'pastor', 'elder', 'rabbi'],
suffixes = ['i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x', 'xi', 'xii', 'xiii', 'xiv', 'xv', 'jr', 'junior', 'sr', 'senior', 'phd', 'md', 'dmd', 'dds', 'esq'],
firstWord = stripName(fullName[0]),
lastWord = stripName(fullName[fullName.length - 1]),
sortName;
if(suffixes.indexOf(lastWord) != -1) {
//Joe M Doe PhD. --> Doe PhD, Joe M
var isSuffix, i = 1;
do {
i++;
var prevWord = stripName(fullName[fullName.length - i]);
isSuffix = suffixes.indexOf(prevWord) != -1;
} while(isSuffix);
if(i != fullName.length) {
var lNameSuffixes = fullName.splice(fullName.length - i, fullName.length - 1);
sortName = lNameSuffixes.join(' ') + ', ' + fullName.join(' ');
} else {
sortName = fullName.join(' ');
}
} else if(articles.indexOf(firstWord) != -1) {
//The Collection of Stories --> Collection of Stories, The
var article = fullName[0];
fullName.splice(0, 1);
sortName = fullName.join(' ') + ', ' + article;
} else {
//John Smith --> Smith, John
var lastName = fullName[fullName.length - 1];
fullName.splice(fullName.length - 1, fullName.length);
sortName = lastName + ', ' + fullName.join(' ');
}
console.log(sortName);
return sortName;
}