One relatively simple way is to split the string on the space, creating an array of each element. Take the first element for the first name, and join the rest of the array back together to form the last name.
var name="Alexandra De Poorter"; var splitName = name.split(" "); var firstName = splitName.shift(); var lastName = splitName.join(" "); var finalname = lastName + ", " + firstName; $.writeln(finalname);
Note that shift() actually removes the first item from the array so you can simply join the rest together without worrying about the first name.
Try this one:
var name = "Alexandra De Poorter"; var fName = name.slice( 0 , name.indexOf(" ") ); var lName = name.slice( name.indexOf(" ") + 1 ); alert ( fName + "\r" + lName + "\r" + fName + " "+ lName );
var name="Alexandra De Poorter"; var parts = name.match(/(.+?) (.+)/); var finalname = parts + ', ' + parts;
A little question, by curiosity:
How manage these cases:
John F. Kennedy
John Fitzgerald Kennedy
Eddy van Halen
Louis Antoine de Saint-Just
Charles de Gaulle
… to obtain:
Kennedy, John F.
Kennedy, John Fitzgerald
van Halen, Eddy
Saint-Just (Louis Antoine de)
de Gaulle (Charles)
Thanks in advance!
Matching names is not so easy, especially because you won't be able to tell the difference between Portuguese and Spanish names such as my niece's name, Lara David Kahrel (who lives in Portugal), whose last name is 'David Kahrel', and John Fitzgerald Kennedy, whose last name is 'Kennedy'. That aside, your examples (and more) can be captured as follows:
var parts = name.match(/^(.+?) ((?:v[ao]n )?(?:d[eu]r? ?)?(?:la ?)?)?([^ ]+)$/i); var finalname = ""; if (parts != "") finalname = parts; // if there are no prefixes, as in 'John Black', then parts == "" finalname += parts + ', ' + parts;
The expression chops strings up in two or three parts: last name (everything from the last space to the end of the string), prefixes (any combination of 'van', 'von', 'van de', etc.), and first name (everything up to the first prefix or up to the last name. In this form it captures these (Dutch, Flemish, German, French) prefixes case-insensitively:
You could add others, such as 't, op, della, etc. etc.
Thanks Peter! And my greetings to your niece!