This example takes the names entered by the user and uppercases the first letter of each name, then lowercases the following letters. Rather than having to account for each little space in a string before upper/lower-casing, we can use the split method to do the dirty work for us.

The split method creates an array whose elements are pieces of the original string. The original string is split by the character value you specify as its parameter. If the parameter you specify is a space, text on either side of a space becomes an individual element.
If there are 5 spaces, one right after the other, 4 elements whose values are empty strings are created. This does not affect our intentions to manipulate the new strings because there's not a lot you can do to an empty string. An empty string plus and empty string equals an empty string. So if we wanted to concatenate each element together, the elements whose values are empty strings are essentially ignored because there is nothing to write. Show all elements together

As you can see from the above example, the names are running together. Manually adding a space after each iteration to solve this problem can create a new problem: it gives the elements whose values are empty strings a value of a space, defeating the purpose of split() altogether. However, a simple if statement that weeds out any empty string elements before adding a space will keep that anomaly from occuring.

Now we have easy access to the first character of each new string. Using a for-loop, we can examine each new string and manipulate it anyway we want. We also make sure we're not adding a space to an empty element.
var name = ""
var nameArray = yourName.split(" ")

for(i=0; i < nameArray.length; i++){

 var firstLetter = nameArray[i].charAt(0).toUpperCase()
 var rest = nameArray[i].substring(1,nameArray[i].length).toLowerCase()

   if(nameArray[i] != "") {
   name += firstLetter + rest + " "

Because the variable name is being added to itself for each iteration of the loop (the first iteration, name equals the first name, the second iteration, names equals first name plus second name, etc..), you must give name an initial value of nothing ("") so that the first interation has a value to add to. You can see this process in the example below, where we've added an alert to the for loop:
name = ""
var splitIt=document.forms[0].elements[0].value.split(' ')
for(i=0; i<splitIt.length; i++) {
alert(name += splitIt[i])

What about Irish names?

View the Source

Home | Contact