How to capitalize each word in a JavaScript string

A SO page has a nice example of how to capitalize each word in a string in JavaScript:

function capitalizeEachWord(str) {
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

You can test this code at JsFiddle.net like this:

var x = "foo bar baz";
var y = capitalizeEachWord(x);
console.log('x = ' + x);   // prints "foo bar baz"
console.log('y = ' + y);   // prints "Foo Bar Baz"

As you can see, this function doesn’t modify the string you give it, but returns a new string with each word capitalized.

Note the use of the regular expression in this code. The string \w\S* matches a “word character” followed by zero or more “non-whitespace characters”. Then, rather than use a replacement pattern, a function is used to process what’s found with the pattern. That’s good stuff.

Another approach using slice and charAt

Another clever approach shows how to use slice and charAt:

function capitalizeEachWord(str) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

I haven’t tested the two functions to see how they work on fringe cases, but at first glance they seem very similar.

Combining capitalize with removing blank spaces

In some code I just wrote, I combine this capitalize function with this function that removes blank spaces in a string:

function removeSpaces(str) {
    return str.replace(/ /g,'');
}

The combination of functions, and resulting output is shown here:

var x = "foo bar baz";
var y = removeSpaces(capitalizeEachWord(x));

console.log('x = ' + x);   // prints "foo bar baz"
console.log('y = ' + y);   // prints "FooBarBaz"

I’ve done a lot of text processing in the last year, and I continue to be amazed at what a programmer can do with pattern matching and regular expressions.