Forum Moderators: open

Message Too Old, No Replies

Separating last name

         

foxroberts

5:10 pm on May 25, 2004 (gmt 0)

10+ Year Member



Hi.

I want to seperate the last name
from a string like "Fox" from
"Michael J. Fox".

I know it is not too difficult
for a pro, but for me.

Thank you for any hints!

Fox

DrDoc

5:18 pm on May 25, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to Webmaster World!

To best help you, let me just ask something first.
What if it's someone with two last names?
Or, do you know for sure that the full name is formatted a certain way?

foxroberts

5:37 pm on May 25, 2004 (gmt 0)

10+ Year Member



Thank you for the welcoming words.

I am sure that the name is formatted correctly.
If a person has two last names, it is
formatted like this: "Peter H. Smith-Miller"

MichaelBluejay

7:25 pm on May 25, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Well, good code should work regardless of whether it's a two- or three-word name.

name = "Julio Gonzalez Escondido de la Rosa";

nameArray = name.split(" "); // Turns the name into array, with each word as a separate element

lastName = nameArray[nameArray.length-1];

alert(lastName); // Test to make sure it works

--------------

The reason you subtract 1 is that the array elements are numbered starting at 0 (0, 1, 2, 3, 4, 5), but the length is the number of items in the array (6).

MichaelBluejay

7:28 pm on May 25, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



P.S. If the last name is actually a multi-word last name, like "de la Rosa", you can see that my script isn't going to work, because it's just going to return "Rosa". To get around that your code could check for specific multi-word name starters like "de la", but you'd have to make sure you knew about all of them.

The other solution is to capture the last name separately from the first name when you're gathering your input in the first place. If the user is filling out a form, have two fields, one for first name and one for last name. That way you can refer to them separately.

foxroberts

8:15 am on May 26, 2004 (gmt 0)

10+ Year Member



Thank you for your help.

I see the "de la Rosa" problem,
but the script is for a
german website and "de la Rosa"
is hard to find over here.

Thank you anyway.
You saved my day.