Home : Internet : JavaScript : Text : Capitalize

Capitalize Words Using JavaScript

This page shows how to capitalize words in a text string using JavaScript (i.e. change the first letter of each word to upper-case). The following example shows how this works:

This script takes the input from the first text field and outputs it to the second. You can adapt the script to accept and output the string in other ways.

Place the following code in the document head. This contains the "capWords" function which does the conversion:

function capWords() {
var inputString = document.form1.instring; // The input text field
var outputString = document.form1.outstring; // The output text field
var tmpStr, tmpChar, preString, postString, strlen;
tmpStr = inputString.value.toLowerCase();
stringLen = tmpStr.length;
if (stringLen > 0)
{
  for (i = 0; i < stringLen; i++)
  {
    if (i == 0)
	{
      tmpChar = tmpStr.substring(0,1).toUpperCase();
      postString = tmpStr.substring(1,stringLen);
      tmpStr = tmpChar + postString;
    }
    else
	{
      tmpChar = tmpStr.substring(i,i+1);
      if (tmpChar == " " && i < (stringLen-1))
	  {
      tmpChar = tmpStr.substring(i+1,i+2).toUpperCase();
      preString = tmpStr.substring(0,i+1);
      postString = tmpStr.substring(i+2,stringLen);
      tmpStr = preString + tmpChar + postString;
      }
    }
  }
}
outputString.value = tmpStr;
}

Place the following code in the document body. This includes two text fields (one for the input and one for the resulting output) and a button to initiate the conversion:

<form name="form1" method="post">
<input name="instring" type="text" value="this is the text string" size="30">
<input type="button" name="Capitalize" value="Capitalize >>" onClick="capWords();">
<input name="outstring" type="text" value="" size="30">
</form>