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

ucwords.js

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

Example usage:

var hello = 'HELLO world';
hello.ucwords();

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

Web Developer, Business Analytics, Data Engineer specialising in PHP, ReactJS, Tableau, AWS RedShift and Matillion ETL

Based in Melbourne, Australia

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

Leave a comment

Name Notify me of replies by email.