in Code

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:
console.log("this text should look nicer now".capitalize());
>> This Text Should Look Nicer Now

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

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

Write a Comment


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