Javascript: Capitalize Text Like In This Title

On this one, we’ll show of the dynamic nature of javascript and we’re going to make all strings have a new method called “capitalize()”.

So you can do stuff like this:
[javascript]
console.log("this text should look nicer now".capitalize());
>> This Text Should Look Nicer Now
[/javascript]

Here’s the magic code you’ll need to add somewhere on your javascript files and all strings will have a new capitalize() method.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.