In this example, you will see how to create a custom capitalize method in javascript . you can extend the prototype object by append a function with dot. Prototype object extends the objects which are inherit from base object. You can create your own extension and load these extension to your page or other library, you can also extend prototype object in any web projects. You can give your file name e.g Prototype.String.js, Prototype.CurrenyFormat.js
Capitalize method will convert all character of a string into lower case and then convert the first letter of each word to upper case, eg.
- welcome to aspxtutorial.com => Welcome To Aspxtutorial.com
- Author: amir hasan => Author: Aamir Hasan
- PROTOTYPE => Prototype
Here’s an example
<script type="text/javascript">
String.prototype.toCapitalize = function () {
return this.toLowerCase().replace(/(^|\s)([a-z])/g, function (g, temp1, temp2) { return temp1 + temp2.toUpperCase(); });
}
</script>
Here , i have created st1, str2 and str3 variables and assign string as shown below.
var str1 = "welcome to aspxtutorial.com";
var str2 = "Author: aamir hasan";
var str3 = "PROTOTYPE";
You can call toCapitalize() to convert first letter of each word in a string. Just add a toCapitalize() function to the String prototype.
alert("Example 1: " + str1.toCapitalize());
alert("Example 2: " + str2.toCapitalize());
alert("Example 3: " + str3.toCapitalize());
Output

Download
Capitalize-method.aspx (1.14 kb)
See live demo