[javascript] How can I capitalize the first letter of each word in a string using JavaScript?

I'm trying to write a function that capitalizes the first letter of every word in a string (converting the string to title case).

For instance, when the input is "I'm a little tea pot", I expect "I'm A Little Tea Pot" to be the output. However, the function returns "i'm a little tea pot".

This is my code:

_x000D_
_x000D_
function titleCase(str) {
  var splitStr = str.toLowerCase().split(" ");

  for (var i = 0; i < splitStr.length; i++) {
    if (splitStr.length[i] < splitStr.length) {
      splitStr[i].charAt(0).toUpperCase();
    }

    str = splitStr.join(" ");
  }

  return str;
}

console.log(titleCase("I'm a little tea pot"));
_x000D_
_x000D_
_x000D_

This question is related to javascript string title-case

The answer is


Here's how you could do it with the map function basically, it does the same as the accepted answer but without the for-loop. Hence, saves you few lines of code.

_x000D_
_x000D_
function titleCase(text) {_x000D_
  if (!text) return text;_x000D_
  if (typeof text !== 'string') throw "invalid argument";_x000D_
_x000D_
  return text.toLowerCase().split(' ').map(value => {_x000D_
    return value.charAt(0).toUpperCase() + value.substring(1);_x000D_
  }).join(' ');_x000D_
}_x000D_
_x000D_
console.log(titleCase("I'm A little tea pot"));
_x000D_
_x000D_
_x000D_


A more compact (and modern) rewrite of @somethingthere's proposed solution:

_x000D_
_x000D_
let titleCase = (str => str.toLowerCase().split(' ').map(
                c => c.charAt(0).toUpperCase() + c.substring(1)).join(' '));
    
document.write(titleCase("I'm an even smaller tea pot"));
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
function titleCase(str) {_x000D_
  //First of all, lets make all the characters lower case_x000D_
  let lowerCaseString = "";_x000D_
  for (let i = 0; i < str.length; i++) {_x000D_
    lowerCaseString = lowerCaseString + str[i].toLowerCase();_x000D_
  }_x000D_
  //Now lets make the first character in the string and the character after the empty character upper case and leave therest as it is_x000D_
  let i = 0;_x000D_
  let upperCaseString = "";_x000D_
  while (i < lowerCaseString.length) {_x000D_
    if (i == 0) {_x000D_
      upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase();_x000D_
    } else if (lowerCaseString[i - 1] == " ") {_x000D_
      upperCaseString = upperCaseString + lowerCaseString[i].toUpperCase();_x000D_
    } else {_x000D_
      upperCaseString = upperCaseString + lowerCaseString[i];_x000D_
    }_x000D_
    i = i + 1;_x000D_
  }_x000D_
  console.log(upperCaseString);_x000D_
_x000D_
  return upperCaseString;_x000D_
}_x000D_
_x000D_
titleCase("hello woRLD");
_x000D_
_x000D_
_x000D_


This routine will handle hyphenated words and words with apostrophe.

function titleCase(txt) {
    var firstLtr = 0;
    for (var i = 0;i < text.length;i++) {
        if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
            firstLtr = 2;
        if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
            firstLtr = 2;
        if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
            if (text.charAt(i) == "'") {
                if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1)))
                    firstLtr = 3;
                else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2)))
                    firstLtr = 3;
            }
        if (firstLtr == 3)
            firstLtr = 1;
        else
            firstLtr = 0;
        }
        if (firstLtr == 2) {
            firstLtr = 1;
            text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
        }
        else {
            text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
        }
    }
}

titleCase("pAt o'Neil's");
// returns "Pat O'Neil's";

You are making complex a very easy thing. You can add this in your CSS:

.capitalize {
    text-transform: capitalize;
}

In JavaScript, you can add the class to an element

 document.getElementById("element").className = "capitalize";

_x000D_
_x000D_
let cap = (str) => {_x000D_
  let arr = str.split(' ');_x000D_
  arr.forEach(function(item, index) {_x000D_
    arr[index] = item.replace(item[0], item[0].toUpperCase());_x000D_
  });_x000D_
_x000D_
  return arr.join(' ');_x000D_
};_x000D_
_x000D_
console.log(cap("I'm a little tea pot"));
_x000D_
_x000D_
_x000D_

Fast Readable Version see benchmark http://jsben.ch/k3JVz enter image description here


function LetterCapitalize(str) { 
  return str.split(" ").map(item=>item.substring(0,1).toUpperCase()+item.substring(1)).join(" ")
}

You can use modern JS syntax which can make your life much easier. Here is my code snippet for the given problem:

_x000D_
_x000D_
const capitalizeString = string => string.split(' ').map(item => item.replace(item.charAt(0), item.charAt(0).toUpperCase())).join(' ');
capitalizeString('Hi! i am aditya shrivastwa')
_x000D_
_x000D_
_x000D_


The function below does not change any other part of the string than trying to convert all the first letters of all words (i.e. by the regex definition \w+) to uppercase.

That means it does not necessarily convert words to Titlecase, but does exactly what the title of the question says: "Capitalize First Letter Of Each Word In A String - JavaScript"

  • Don't split the string
  • determine each word by the regex \w+ that is equivalent to [A-Za-z0-9_]+
    • apply function String.prototype.toUpperCase() only to the first character of each word.
function first_char_to_uppercase(argument) {
  return argument.replace(/\w+/g, function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
}

Examples:

first_char_to_uppercase("I'm a little tea pot");
// "I'M A Little Tea Pot"
// This may look wrong to you, but was the intended result for me
// You may wanna extend the regex to get the result you desire, e.g., /[\w']+/

first_char_to_uppercase("maRy hAd a lIttLe LaMb");
// "MaRy HAd A LIttLe LaMb"
// Again, it does not convert words to Titlecase

first_char_to_uppercase(
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
// "ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples"

first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
// "…N1=OrangesFromSPAIN&&N2!='A Sub-String Inside'"

first_char_to_uppercase("snake_case_example_.Train-case-example…");
// "Snake_case_example_.Train-Case-Example…"
// Note that underscore _ is part of the RegEx \w+

first_char_to_uppercase(
  "Capitalize First Letter of each word in a String - JavaScript"
);
// "Capitalize First Letter Of Each Word In A String - JavaScript"

Edit 2019-02-07: If you want actual Titlecase (i.e. only the first letter uppercase all others lowercase):

function titlecase_all_words(argument) {
  return argument.replace(/\w+/g, function(word) {
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  });
}

Examples showing both:

test_phrases = [
  "I'm a little tea pot",
  "maRy hAd a lIttLe LaMb",
  "ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
  "…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
  "snake_case_example_.Train-case-example…",
  "Capitalize First Letter of each word in a String - JavaScript"
];
for (el in test_phrases) {
  let phrase = test_phrases[el];
  console.log(
    phrase,
    "<- input phrase\n",
    first_char_to_uppercase(phrase),
    "<- first_char_to_uppercase\n",
    titlecase_all_words(phrase),
    "<- titlecase_all_words\n "
  );
}

// I'm a little tea pot <- input phrase
// I'M A Little Tea Pot <- first_char_to_uppercase
// I'M A Little Tea Pot <- titlecase_all_words

// maRy hAd a lIttLe LaMb <- input phrase
// MaRy HAd A LIttLe LaMb <- first_char_to_uppercase
// Mary Had A Little Lamb <- titlecase_all_words

// ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples <- input phrase
// ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples <- first_char_to_uppercase
// Examplex: Camelcase/Uppercase&Lowercase,Exampley:N0=Apples <- titlecase_all_words

// …n1=orangesFromSPAIN&&n2!='a sub-string inside' <- input phrase
// …N1=OrangesFromSPAIN&&N2!='A Sub-String Inside' <- first_char_to_uppercase
// …N1=Orangesfromspain&&N2!='A Sub-String Inside' <- titlecase_all_words

// snake_case_example_.Train-case-example… <- input phrase
// Snake_case_example_.Train-Case-Example… <- first_char_to_uppercase
// Snake_case_example_.Train-Case-Example… <- titlecase_all_words

// Capitalize First Letter of each word in a String - JavaScript <- input phrase
// Capitalize First Letter Of Each Word In A String - JavaScript <- first_char_to_uppercase
// Capitalize First Letter Of Each Word In A String - Javascript <- titlecase_all_words

I think this way should be faster; cause it doesn't split string and join it again; just using regex.

var str = text.replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());

Explanation:

  1. (^\w{1}): match first char of string
  2. |: or
  3. (\s{1}\w{1}): match one char that came after one space
  4. g: match all
  5. match => match.toUpperCase(): replace with can take function, so; replace match with upper case match

ECMAScript 6 version:

title
    .split(/ /g).map(word =>
        `${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
    .join(" ");

I used replace() with a regular expression:

function titleCase(str) {

  var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());

  console.log(newStr);
}

titleCase("I'm a little tea pot")

-

You could simply use a regular expression function to change the capitalization of each letter. With V8 JIST optimizations, this should prove to be the fast and memory efficient.

// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})

Or, as a function:

// Only works for Latin-I strings
var fromCharCode = String.fromCharCode;
var firstLetterOfWordRegExp = /\b[a-z]|['_][a-z]|\B[A-Z]/g;
function toLatin1UpperCase(x){ // avoid frequent anonymous inline functions
    var charCode = x.charCodeAt(0);
    return charCode===39 ? x : fromCharCode(charCode^32);
}
function titleCase(string){
    return string.replace(firstLetterOfWordRegExp, toLatin1UpperCase);
}

According to this benchmark, the code is over 33% faster than the next best solution in Chrome.


_x000D_
_x000D_
<textarea id="input" type="text">I'm a little tea pot</textarea><br /><br />_x000D_
<textarea id="output" type="text" readonly=""></textarea>_x000D_
<script>_x000D_
(function(){_x000D_
    "use strict"_x000D_
    var fromCode = String.fromCharCode;_x000D_
    function upper(x){return x[0]==="'"?x:fromCode(x.charCodeAt(0) ^ 32)}_x000D_
    (input.oninput = function(){_x000D_
      output.value = input.value.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, upper);_x000D_
    })();_x000D_
})();_x000D_
</script>
_x000D_
_x000D_
_x000D_


ES6 syntax

const captilizeAllWords = (sentence) => {
  if (typeof sentence !== "string") return sentence;
  return sentence.split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}


captilizeAllWords('Something is going on here')

In ECMAScript 6, a one-line answer using the arrow function:

const captialize = words => words.split(' ').map( w =>  w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')

Shortest One Liner (also extremely fast):

 text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());

Explanation:

  • ^\w : first character of the string
  • | : or
  • \s\w : first character after whitespace
  • (^\w|\s\w) Capture the pattern.
  • g Flag: Match all occurrences.

If you want to make sure the rest is in lowercase:

text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())

Also a good option (particularly if you're using freeCodeCamp):

function titleCase(str) {
  var wordsArray = str.toLowerCase().split(/\s+/);
  var upperCased = wordsArray.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substr(1);
  });
  return upperCased.join(" ");
}

A complete and simple solution goes here:

String.prototype.replaceAt=function(index, replacement) {
        return this.substr(0, index) + replacement+ this.substr(index
  + replacement.length);
}
var str = 'k j g           u              i l  p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
    for(let i  = 0; i < str.length-1; i++) {
        if(str[i] === ' ' && str[i+1] !== '')
            str = str.replaceAt(i+1, str[i+1].toUpperCase());
    }
    return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));

text-transform: capitalize;

CSS has got it :)


ECMAScript 6 version:

_x000D_
_x000D_
const toTitleCase = (phrase) => {
  return phrase
    .toLowerCase()
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
};

let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);
_x000D_
_x000D_
_x000D_


/* 1. Transform your string into lower case
   2. Split your string into an array. Notice the white space I'm using for the separator
   3. Iterate the new array, and assign the current iteration value (array[c]) a new formatted string:
      - With the sentence: array[c][0].toUpperCase() the first letter of the string converts to upper case.
      - With the sentence: array[c].substring(1) we get the rest of the string (from the second letter index to the last one).
      - The "add" (+) character is for concatenate both strings.
   4. return array.join(' ') // Returns the formatted array like a new string. */


function titleCase(str){
    str = str.toLowerCase();
    var array = str.split(' ');
    for(var c = 0; c < array.length; c++){
        array[c] = array[c][0].toUpperCase() + array[c].substring(1);
    }
    return array.join(' ');
}

titleCase("I'm a little tea pot");

function titleCase(str) {

    var myString = str.toLowerCase().split(' ');
    for (var i = 0; i < myString.length; i++) {
        var subString = myString[i].split('');
        for (var j = 0; j < subString.length; j++) {
            subString[0] = subString[0].toUpperCase();
        }
        myString[i] = subString.join('');
    }

    return myString.join(' ');
}

If you can use a third-party library then Lodash has a helper function for you.

https://lodash.com/docs/4.17.3#startCase

_x000D_
_x000D_
_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'

_.startCase('fooBar');
// => 'Foo Bar'

_.startCase('__FOO_BAR__');
// => 'FOO BAR'
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


Please check the code below.

function titleCase(str) {
  var splitStr = str.toLowerCase().split(' ');
  var nstr = ""; 
  for (var i = 0; i < splitStr.length; i++) {
    nstr +=  (splitStr[i].charAt(0).toUpperCase()+ splitStr[i].slice(1) + " 
    ");
  }
  console.log(nstr);
}

var strng = "this is a new demo for checking the string";
titleCase(strng);

Or it can be done using replace(), and replace each word's first letter with its "upperCase".

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(word) {
               return word.replace(word[0], word[0].toUpperCase());
           }).join(' ');
}

titleCase("I'm a little tea pot");

Here I used the replace() function.

function titleCase(str){
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

Here I have used three functions toLowerCase(), toUpperCase() and replace(regex,replacer)

function titleCase(str) { 
     return str.toLowerCase().replace(/^(\w)|\s(\w)/g, (grp) => grp.toUpperCase()); 
}

titleCase("I'm a little tea pot");


Raw code:

function capi(str) {
    var s2 = str.trim().toLowerCase().split(' ');
    var s3 = [];
    s2.forEach(function(elem, i) {
        s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
    });
    return s3.join(' ');
}
capi('JavaScript string exasd');

As of ECMA2017 or ES8

_x000D_
_x000D_
const titleCase = (string) => {_x000D_
  return string_x000D_
    .split(' ')_x000D_
    .map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length))_x000D_
    .join(' ');_x000D_
};_x000D_
_x000D_
let result = titleCase('test test test');_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_
Explanation:
1. First, we pass the string "test test test" to our function "titleCase".
2. We split a string on the space basis so the result of first function "split" will be ["test","test","test"]
3. As we got an array, we used map function for manipulation each word in the array. We capitalize the first character and add remaining character to it.
4. In the last, we join the array using space as we split the string by sapce.


let str = "I'm a little tea pot";

str = str.toLowerCase();

and add css property text-transform: capitalize; to the respective element.


Below is another way to capitalize the first alphabet of each word in a string.

Create a custom method for a String object by using prototype.

String.prototype.capitalize = function() {
    var c = '';
    var s = this.split(' ');
    for (var i = 0; i < s.length; i++) {
        c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
    }
    return c;
}
var name = "john doe";
document.write(name.capitalize());

I usually prefer not to use regexp because of readability and also I try to stay away from loops. I think this is kind of readable.

function capitalizeFirstLetter(string) {
    return string && string.charAt(0).toUpperCase() + string.substring(1);
};

This is a simple method to convert and is able to pass a value to get the desired output.

String.prototype.toChangeCase = function (type) {
    switch (type) {
        case 'upper-first':
            return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase();
        case 'upper-each':
            return this.split(' ').map(word => {
                return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
            }).join(' ');
        default:
            throw Error(`In order to get the output pass a value 'upper-first', 'upper-each'`);
    }
}

Outputs

"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-first')
"Capitalize first letter of each word in a sstring"


"capitalize first Letter of Each word in a Sstring".toChangeCase('upper-each')
"Capitalize First Letter Of Each Word In A Sstring"

"Capitalize First Letter Of Each Word In A String".toChangeCase()
VM380:12 Uncaught Error: In order to get the output pass a value 'upper-first', 'upper-each'
    at String.toChangeCase (<anonymous>:12:19)
    at <anonymous>:16:52