vsync vsync - 6 months ago 69
Javascript Question

Capitalize words in string

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

Ivo Ivo

The shortest implementation for capitalizing words within a string is the following using ES6's arrow functions:

'your string'.replace(/\b\w/g, l => l.toUpperCase())
// => 'Your String'

ES5 compatible implementation:

'your string'.replace(/\b\w/g, function(l){ return l.toUpperCase() })
// => 'Your String'

The regex basically matches the first letter of each word within the given string and transforms only that letter to uppercase:

  • \b matches a word boundary (the beginning or ending of word);
  • \w matches the following meta-character [a-zA-Z0-9].