To account for any extra spaces in the string named "yourName", the first thing we want to do is get rid of them. The "chopSpaces()" function chops off the spaces if they are present, so that the value of yourName is corrected before we even begin to seperate each name. Using a for loop, we iterate through each position of the string. Inside the loop are three if statements. Because charAt returns the
value of a character, each if statement uses charAt to test for the occurrence of the space character .
function chopSpaces(){
var yourName = document.cover.name.value
initialLength = yourName.length
// need initial length for use in for loop's condition
for(i = 0; i < initialLength; i++){
The first if statement checks to see if there is a space at position zero. If there is, we use a substring to change the value of yourName by setting its starting point at position one. Since we're in a loop, this will happen as many times as needed.
if(yourName.charAt(0)==" "){
yourName = yourName.substring(1,yourName.length)
}
The next if statement checks for spaces after the first space. If a space is found after the first space, the replace method is used to replace the space with an empty string (""). Because we've only told it to look for a space after the first space, it also chops spaces from the beginning. But after all the spaces have been removed from the beginning, the first occurrence of a space will be located after the first name.
if(yourName.charAt(yourName.indexOf(" ")+1) == " "){
yourName = yourName.replace(yourName.charAt(yourName.indexOf(" ")+1),"")
}
The last if statement checks the value of the last character by using string.length-1. If that value is a space, a substring is again used to change the value of yourName by setting its ending point equal to the space. Remember - the 2nd parameter of the substring is not included in the value, just everything before it.
if(yourName.charAt(yourName.length-1)==" "){
yourName = yourName.substring(0,yourName.lastIndexOf(" "))
}
}
return yourName
}
After the extra spaces are chopped off, the new value of yourName is returned to another function which can safely extract the 3 individual names using any method.
You may be wondering why we didn't account for additional spaces after the middle name. Actually we did, but not in the first function. In the threeNames function, where the 3 individual names are extracted from yourName, is where those are accounted for. It was much easier to do it then rather than in the for loop.
View the Source