First character of each word to uppercase in JavaScript

Here we introducing a function 'ucwords'. Which is used for convert the first character of each word to uppercase in JavaScript. In PHP a built-in function named 'ucwords' is used to uppercase the first character of each word in a string. But in JavaScript there is no equivalent built-in function.

function ucwords(str)
{
    return str === null ? "" : str.toLowerCase().replace(/^(.)|\s+(.)/g, function ($1)
    {
        return $1.toUpperCase();
    });
}
Eg:
ucwords("CONVERT the fIRst character of each word to uppercase in javascript");
ucwords("convert the first character of each word to uppercase in javascript");
ucwords("CONVERT THE FIRST CHARACTER OF EACH WORD TO UPPERCASE IN JAVASCRIPT");
ucwords("Convert the first character of each word to uppercase in javascript");

The above all sentences are converted to
"Convert The First Character Of Each Word To Uppercase In Javascript"

No comments:

Post a Comment