Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize words in string [duplicate]

People also ask

How do you capitalize every word in a string?

Use title() to capitalize the first letter of each word in a string in python. Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.

How do you capitalize letters in a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you capitalize the first letter of each word in a string?

In JavaScript, we have a method called toUpperCase() , which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase. For instance: const publication = "freeCodeCamp"; publication[0].

How do you capitalize text in JavaScript?

The toUpperCase() method converts the string to uppercase. Here, str. charAt(0). toUpperCase(); gives J.


/**
 * 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]

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].

For non-ASCII characters refer to this solution instead

'ÿöur striñg'.replace(/(^|\s)\S/g, l => l.toUpperCase())

This regex matches the first letter and every non-whitespace letter preceded by whitespace within the given string and transforms only that letter to uppercase:

  • \s matches a whitespace character
  • \S matches a non-whitespace character
  • (x|y) matches any of the specified alternatives

A non-capturing group could have been used here as follows /(?:^|\s)\S/g though the g flag within our regex wont capture sub-groups by design anyway.

Cheers!


function capitalize(s){
    return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};

capitalize('this IS THE wOrst string eVeR');

output: "This Is The Worst String Ever"

Update:

It appears this solution supersedes mine: https://stackoverflow.com/a/7592235/104380


The answer provided by vsync works as long as you don't have accented letters in the input string.

I don't know the reason, but apparently the \b in regexp matches also accented letters (tested on IE8 and Chrome), so a string like "località" would be wrongly capitalized converted into "LocalitÀ" (the à letter gets capitalized cause the regexp thinks it's a word boundary)

A more general function that works also with accented letters is this one:

String.prototype.toCapitalize = function()
{ 
   return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}

You can use it like this:

alert( "hello località".toCapitalize() );

A simple, straightforward (non-regex) solution:

const capitalizeFirstLetter = s => 
  s.split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')
  1. Break the string into words Array (by space delimiter)
  2. Break each word to first character + rest of characters in the word
  3. The first letter is transformed to uppercase, and the rest remains as-is
  4. Joins back the Array into a string with spaces

Ivo's answer is good, but I prefer to not match on \w because there's no need to capitalize 0-9 and A-Z. We can ignore those and only match on a-z.

'your string'.replace(/\b[a-z]/g, match => match.toUpperCase())
// => 'Your String'

It's the same output, but I think clearer in terms of self-documenting code.