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). Place the following code in the document head. This contains the "capitalize" function which does the conversion:

String.prototype.capitalize = function(){
 return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};

Usage

capitalizedString = someString.capitalize();

Example

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).

Put this function in the document head (along with the capitalize function above):

function capWords() {
var inputString = document.form1.instring; // The input text field
var outputString = document.form1.outstring; // The output text field
outputString.value = inputString.value.capitalize();
}

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>
Subscribe to us on YouTube