Javascript - Capitalize Each Word in a String

This is a great little function that I whipped up and use to capitalize every word in a string. I can't tell you how many times I've had to use this. Hope you find it useful as I have!

<script type="text/javascript">
function wordToUpper(strSentence) {
    return strSentence.toLowerCase().replace(/\b[a-z]/g, convertToUpper);

    function convertToUpper() {
        return arguments[0].toUpperCase();
    }
}
</script>

1 comments for Javascript - Capitalize Each Word in a String

Martin's picture

Thanks for this helpful...

Thanks for this helpful tidbit! I had a similar need and your function provided the answer. In my case, I had to get the first letter of each word in a string (for initials of a person), so this is what mine looks like:

initials = firstnames.match(/\b[a-z]/g).join("").toUpperCase();

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.