Capitalize words in string

vsync picture vsync · Feb 25, 2010 · Viewed 203.8k times · Source

What is the best approach to capitalize words in a string?

Answer

disfated picture disfated · Sep 29, 2011
/**
 * Capitalizes first letters of words in string.
 * @param {string} str String to be modified
 * @param {boolean=false} lower Whether all other letters should be lowercased
 * @return {string}
 * @usage
 *   capitalize('fix this string');     // -> 'Fix This String'
 *   capitalize('javaSCrIPT');          // -> 'JavaSCrIPT'
 *   capitalize('javaSCrIPT', true);    // -> 'Javascript'
 */
const capitalize = (str, lower = false) =>
  (lower ? str.toLowerCase() : str).replace(/(?:^|\s|["'([{])+\S/g, match => match.toUpperCase());
;

  • fixes Marco Demaio's solution where first letter with a space preceding is not capitalized.
capitalize(' javascript'); // -> ' Javascript'
  • can handle national symbols and accented letters.
capitalize('бабушка курит трубку');  // -> 'Бабушка Курит Трубку'
capitalize('località àtilacol')      // -> 'Località Àtilacol'
  • can handle quotes and braces.
capitalize(`"quotes" 'and' (braces) {braces} [braces]`);  // -> "Quotes" 'And' (Braces) {Braces} [Braces]