Account for spaces at the end of the last name
If we used lastIndexOf(" ") as substring parameters for the middle and last names like we did in
this example, and the user hit the space bar after entering their full name, we'd end up with a useless script. To avoid that potential error, we'll use the optional 2nd parameter available to the indexOf() method as substring parameters for our middle and last name.
string.indexOf(" ",5)
To refresh your memory, the 2nd parameter specifies
where in the string to begin searching for the 1st parameter. The above statement is saying, find the first instance of a space but start looking at position 5.
This is safer than relying on lastIndexOf(" ") because lastIndexOf(" ") will only produce expected results if there are no spaces at the end of the last name.
Since either parameter can be any expression representing an integer, and we have no idea at which position the 2nd space will be, we can say:
string.indexOf(" ",string.indexOf(" ")+1)
This statement is saying, "look for the first occurrence of a space starting
after the first occurrence of a space". It will always return the space immediately following the middle name, assuming there are no spaces before the first name and no more than one space around the middle name. Using this technique, we are no longer reliant on the last instance of a space to find the individual names. Because of this, there can be as many spaces at the end as the reckless user wants to put there.
Now this statement can be used as the second parameter of substring to find the middle name, and the first parameter of substring to find the last name:
var yourName = "billy bob zeek"
var whereToLook = yourName.indexOf(" ",yourName.indexOf(" ")+1)
// look for the first instance of a space starting after the first instance of a space
var middleName = yourName.substring(yourName.indexOf(" "),whereToLook)
var lastName = yourName.substring(whereToLook, yourName.length)
Now lets talk about the return keywords used throughout the function. The return keyword will return the value of the variable we specify,
back to where it is called from.
A function will only return one value. But by using an argument and some if statements, we can cause the function to return 3 different values. The catch is that you must call the function 3 times, specifying a different value for the argument each time. This construct allows us to avoid writing 4 different functions for each of the 4 values we need.
Even though our script now accounts for spaces at the end of the last name, we still have assumed an awful lot with this script. We've assumed that the user will not place spaces before the first name, and more than one space before and after the middle name. As you know, you can
never make assumptions like this about users.
Accounting for any additional spaces throughout the string.
View the Source