Capitalize words in string

JavascriptStringCapitalization

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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!

Solution 3 - Javascript

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

Solution 4 - Javascript

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() );

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

Since everyone has given you the JavaScript answer you've asked for, I'll throw in that the CSS property text-transform: capitalize will do exactly this.

I realize this might not be what you're asking for - you haven't given us any of the context in which you're running this - but if it's just for presentation, I'd definitely go with the CSS alternative.

Solution 8 - Javascript

Using JavaScript and html

String.prototype.capitalize = function() {
  return this.replace(/(^|\s)([a-z])/g, function(m, p1, p2) {
    return p1 + p2.toUpperCase();
  });
};

<form name="form1" method="post">
  <input name="instring" type="text" value="this is the text string" size="30">
  <input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();">
  <input name="outstring" type="text" value="" size="30">
</form>

Basically, you can do string.capitalize() and it'll capitalize every 1st letter of each word.

Source: http://www.mediacollege.com/internet/javascript/text/case-capitalize.html

Solution 9 - Javascript

John Resig (of jQuery fame ) ported a perl script, written by John Gruber, to JavaScript. This script capitalizes in a more intelligent way, it doesn't capitalize small words like 'of' and 'and' for example.

You can find it here: Title Capitalization in JavaScript

Solution 10 - Javascript

My solution:

String.prototype.toCapital = function () {
    return this.toLowerCase().split(' ').map(function (i) {
        if (i.length > 2) {
            return i.charAt(0).toUpperCase() + i.substr(1);
        }

        return i;
    }).join(' ');
};

Example:

'álL riGht'.toCapital();
// Returns 'Áll Right'

Solution 11 - Javascript

If you're using lodash in your JavaScript application, You can use _.capitalize:

console.log( _.capitalize('ÿöur striñg') );
 

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

Solution 12 - Javascript

This should cover most basic use cases.

const capitalize = (str) => {
    if (typeof str !== 'string') {
      throw Error('Feed me string')
    } else if (!str) {
      return ''
    } else {
      return str
        .split(' ')
        .map(s => {
            if (s.length == 1 ) {
                return s.toUpperCase()
            } else {
                const firstLetter = s.split('')[0].toUpperCase()
                const restOfStr = s.substr(1, s.length).toLowerCase()
                return firstLetter + restOfStr
            }     
        })
        .join(' ')
    }
}


capitalize('THIS IS A BOOK') // => This Is A Book
capitalize('this is a book') // => This Is A Book
capitalize('a 2nd 5 hour boOk thIs weEk') // => A 2nd 5 Hour Book This Week

Edit: Improved readability of mapping.

Solution 13 - Javascript

This solution dose not use regex, supports accented characters and also supported by almost every browser.

function capitalizeIt(str) {
    if (str && typeof(str) === "string") {
        str = str.split(" ");    
        for (var i = 0, x = str.length; i < x; i++) {
            if (str[i]) {
                str[i] = str[i][0].toUpperCase() + str[i].substr(1);
            }
        }
        return str.join(" ");
    } else {
        return str;
    }
}    

Usage:

> console.log(capitalizeIt('çao 2nd inside Javascript programme'));

Output:

> Çao 2nd Inside Javascript Programme

Solution 14 - Javascript

http://www.mediacollege.com/internet/javascript/text/case-capitalize.html is one of many answers out there.

Google can be all you need for such problems.

A naïve approach would be to split the string by whitespace, capitalize the first letter of each element of the resulting array and join it back together. This leaves existing capitalization alone (e.g. HTML stays HTML and doesn't become something silly like Html). If you don't want that affect, turn the entire string into lowercase before splitting it up.

Solution 15 - Javascript

This code capitalize words after dot:

function capitalizeAfterPeriod(input) { 
    var text = '';
    var str = $(input).val();
    text = convert(str.toLowerCase().split('. ')).join('. ');
    var textoFormatado = convert(text.split('.')).join('.');
    $(input).val(textoFormatado);
}

function convert(str) {
   for(var i = 0; i < str.length; i++){
      str[i] = str[i].split('');
      if (str[i][0] !== undefined) {
         str[i][0] = str[i][0].toUpperCase();
      }
      str[i] = str[i].join('');
   }
   return str;
}

Solution 16 - Javascript

I like to go with easy process. First Change string into Array for easy iterating, then using map function change each word as you want it to be.

function capitalizeCase(str) {
    var arr = str.split(' ');
    var t;
    var newt;
    var newarr = arr.map(function(d){
        t = d.split('');
        newt = t.map(function(d, i){
                  if(i === 0) {
                     return d.toUpperCase();
                    }
                 return d.toLowerCase();
               });
        return newt.join('');
      });
    var s = newarr.join(' ');
    return s;
  }

Solution 17 - Javascript

Jquery or Javascipt doesn't provide a built-in method to achieve this.

CSS test transform (text-transform:capitalize;) doesn't really capitalize the string's data but shows a capitalized rendering on the screen.

If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>

var capitalizeString = function (word) {    
    word = word.toLowerCase();
    if (word.indexOf(" ") != -1) { // passed param contains 1 + words
        word = word.replace(/\s/g, "--");
        var result = $.camelCase("-" + word);
        return result.replace(/-/g, " ");
    } else {
    return $.camelCase("-" + word);
    }
}

Solution 18 - Javascript

Use This:

String.prototype.toTitleCase = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

let str = 'text';
document.querySelector('#demo').innerText = str.toTitleCase();

<div class = "app">
  <p id = "demo"></p>
</div>

Solution 19 - Javascript

You can use the following to capitalize words in a string:

function capitalizeAll(str){

    var partes = str.split(' ');

    var nuevoStr = ""; 

    for(i=0; i<partes.length; i++){
	nuevoStr += " "+partes[i].toLowerCase().replace(/\b\w/g, l => l.toUpperCase()).trim(); 
    }    

    return nuevoStr;

}

Solution 20 - Javascript

There's also locutus: https://locutus.io/php/strings/ucwords/ which defines it this way:

function ucwords(str) {
  //  discuss at: http://locutus.io/php/ucwords/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Waldo Malqui Silva (http://waldo.malqui.info)
  // improved by: Robin
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // bugfixed by: Cetvertacov Alexandr (https://github.com/cetver)
  //    input by: James (http://www.james-bell.co.uk/)
  //   example 1: ucwords('kevin van  zonneveld')
  //   returns 1: 'Kevin Van  Zonneveld'
  //   example 2: ucwords('HELLO WORLD')
  //   returns 2: 'HELLO WORLD'
  //   example 3: ucwords('у мэри был маленький ягненок и она его очень любила')
  //   returns 3: 'У Мэри Был Маленький Ягненок И Она Его Очень Любила'
  //   example 4: ucwords('τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός')
  //   returns 4: 'Τάχιστη Αλώπηξ Βαφής Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνός'

  return (str + '').replace(/^(.)|\s+(.)/g, function ($1) {
    return $1.toUpperCase();
  });
};

Solution 21 - Javascript

I would use regex for this purpose:

myString = '  this Is my sTring.  ';
myString.trim().toLowerCase().replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvsyncView Question on Stackoverflow
Solution 1 - JavascriptdisfatedView Answer on Stackoverflow
Solution 2 - JavascriptIvoView Answer on Stackoverflow
Solution 3 - JavascriptvsyncView Answer on Stackoverflow
Solution 4 - JavascriptMarco DemaioView Answer on Stackoverflow
Solution 5 - JavascriptOtman ZaibView Answer on Stackoverflow
Solution 6 - JavascriptBig MoneyView Answer on Stackoverflow
Solution 7 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 8 - JavascriptBuhake SindiView Answer on Stackoverflow
Solution 9 - JavascriptmeouwView Answer on Stackoverflow
Solution 10 - JavascriptErick TatsuiView Answer on Stackoverflow
Solution 11 - Javascriptvicke4View Answer on Stackoverflow
Solution 12 - JavascriptDropsView Answer on Stackoverflow
Solution 13 - JavascriptNabarag PaulView Answer on Stackoverflow
Solution 14 - JavascriptAlan PlumView Answer on Stackoverflow
Solution 15 - JavascriptFlavioView Answer on Stackoverflow
Solution 16 - JavascriptMritunjay UpadhyayView Answer on Stackoverflow
Solution 17 - JavascriptsiwalikmView Answer on Stackoverflow
Solution 18 - JavascriptSanjayView Answer on Stackoverflow
Solution 19 - JavascriptMarcos TorresView Answer on Stackoverflow
Solution 20 - JavascriptgeoidesicView Answer on Stackoverflow
Solution 21 - JavascriptAbdulmoiz AhmerView Answer on Stackoverflow