Capitalize words in string using javascript

In this programming tutorial we will learn how to capitalize words in string using javascript. The functionality of prototype can be extended by appending a custom function after dot. Prototype object extends the objects which are inherit from base object. We can create our own extension and load these extension to our page or library. We can also give our file name like this Prototype.CapitalizeWords.js, Prototype.FormatCurrency.js. Let's have a look over the code snippet given below
Capitalize words in string using javascript

Copy/paste the following code in the <head> section of your page.

<script language="javascript" type="text/javascript">
String.prototype.toCapitalize = function()
{ 
   return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}
//And this is the way to call the toCapitalize() function
alert("Muhammad Ali".toCapitalize());

alert("ADEEL FAKHAR".toCapitalize());

alert("shoaib akhtar".toCapitalize());

</script>

So that's it.
I love your feedback.

0 comments: