Last active
August 29, 2015 14:04
-
-
Save yankeyhotel/9ce9d3e346497586fd0f to your computer and use it in GitHub Desktop.
A function to parse names into an object with Javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var name_obj = {}, | |
prefixes = ["Ms.", "Miss.", "Mrs.", "Mr."], | |
suffixes = ["Esq.", "Jr.", "Sr."]; | |
function parse(value) { | |
/* ----------------------------------------------- | |
* depending on the requirements you might need to | |
* remove punctuation and/or change to lowercase | |
* for easier searching | |
* ----------------------------------------------- | |
* // search in lowercase | |
* value = value.toLowerCase(); | |
* // remove periods | |
* value = value.replace(/\./g, ""); | |
*/ | |
// split the string into an array | |
var str_array = value.split(" "); | |
// see if the first element is a prefix | |
if ( prefixes.indexOf(str_array[0]) >= 0 ) { | |
name_obj.prefix = str_array.shift(); | |
} else { | |
name_obj.prefix = null; | |
} | |
// see if the last element is a suffix | |
if ( suffixes.indexOf(str_array[str_array.length-1]) >= 0 ) { | |
name_obj.suffix = str_array.pop(); | |
} else { | |
name_obj.suffix = null; | |
} | |
// assume that the first element is the first name | |
// and the last element is the last name | |
name_obj.first = str_array.shift(); | |
name_obj.last = str_array.pop(); | |
// might as well save everything that's left over | |
name_obj.middle_etc = str_array.join(" "); | |
console.log(name_obj); | |
} | |
parse("Mr. Matt Wayne Theodore McClard Esq."); | |
// alert(name_obj.first); | |
// alert(name_obj.last); | |
parse("Matt McClard Sr."); | |
// alert(name_obj.first); | |
// alert(name_obj.last); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment