Ucwords for Javascript

PHP has a great function ucwords that uppercases the first character of each word in a string. So hello world becomes Hello World.

Javascript and jQuery are both missing this usefull function so I mashed together the below port of ucwords to javascript


String.prototype.ucwords = function() {
    str = this.toLowerCase();
    return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g,
            return $1.toUpperCase();

Example usage:

var hello = 'HELLO world';

This will convert HELLO world to Hello World, etc..

Note: A pure port of PHPs ucwords would remove the str = this.toLowerCase(); line so as leave capitalised words as it

Justin Kelly

Justin Kelly

Data Engineeer, Business Analytics, Web Developer, Library Technology specialising in PHP and Tableau

Based in Melbourne, Australia

Feel free to contact me justin@kelly.org.au or _justin_kelly