Design & Download
Your JS Library
in Seconds!!!

Snippet: titleCase() - Title Casing Strings

Written by Christopher West (cwest) on November 14, 2015.
Capitalizes the first letter of each word in a string. Also commonly known as toProperCase().
var titleCase;
(function(RGX_WORD) {
  titleCase = function (str, opt_fnFilter) {
    return str.replace(RGX_WORD, function(word, start, rest, index) {
      return (!opt_fnFilter || opt_fnFilter(word, index, str) ? start.toUpperCase() : start) + rest;
    });
  };
})(/(\S)((?:\B\S)*)/g);

In some JavaScript libraries this function is known as String.prototype.toProperCase(), but seeing as how I am getting away from modifying native prototypes I decided to also change the number from "proper case" to "title case". In addition, this function does a little more because it gives you the ability to define a filtering function to filter out any words that you may not want to title case.

titleCase(...) API Documentation

Description

Capitalizes the first letter of each word in a string.

Parameters

  1. str {String}:
    The string which will be title cased.
  2. opt_fnFilter {function(word, position, originalString) -> boolean}:
    Optional. If specified, this function will be passed every word (along with the position and the originalString) and should return true if the word should be title cased, otherwise false should be returned.

Returns

Returns str with all of the 1st letter of each word capitalized (unless filtered out by opt_fnFilter).

Examples

console.log(YourJS.titleCase('hello'));          // -> 'Hello'
console.log(YourJS.titleCase('hello world!!!')); // -> 'Hello World!!!'
console.log(YourJS.titleCase('u.s.a.'));         // -> 'U.S.A.'