Easily add PHP's UCWords & UCFirst to JavaScript

While JavaScript has the handy toUpperCase() and toLowerCase() string methods. There is not a function equivalent to PHP's useful text manipulation function ucwords() or ucfirst(), but you can create the same functionality by adding these functions to your script.

ucwords()

Returns a string with the first character of each word in str capitalized, if that character is alphabetic. PHP Docs
Here is how you can get the same functionality as ucwords(), in plain vanilla JavaScript (no jQuery needed). Add this to your JavaScript file:
  String.prototype.toUpperCaseWords = function () {
    return this.replace(/\w+/g, function(a){ 
      return a.charAt(0).toUpperCase() + a.slice(1).toLowerCase()
    })
  }
Then use like so:
"MY LOUD STRING".toUpperCaseWords(); // Output: My Loud String
"my quiet string".toUpperCaseWords(); // Output: My Quiet String

var stringVariable = "First put into a var";

stringVariable.toUpperCaseWords(); // Output: First Put Into A Var

ucfirst()

Returns a string with the first character of str capitalized, if that character is alphabetic. PHP Docs
Add this to your JavaScript file:
  String.prototype.toUpperCaseFirst = function () {
     return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase()
  }
Then use by:
"MY LOUD STRING".toUpperCaseFirst(); // Output: My loud string
"my quiet string".toUpperCaseFirst(); // Output: My quiet string

var stringVariable = "First put into a var";

stringVariable.toUpperCaseFirst(); // Output: First put into a var
Small dog web development studio

View All Our Posts

Web application developers in western Washington, creating user centric web solutions for businesses of all shapes and sizes.

Our projects include ecommerce, event organization, user driven web applications and more.


Small Dog Studios, LLC. Small Dog Studios News