233

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:

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"));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
slurrr
  • 2,534
  • 2
  • 11
  • 10
  • That does not look like it capitalizes the first letter of just a string. Or do you mean you want to capitalize each word contained in the string. – epascarello Sep 15 '15 at 14:54
  • 3
    You are not assigining your capitalisation to your result, the `splitStr[i].charAt(0).toUpperCase();` is going to `void`. You need to do `splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);` – somethinghere Sep 15 '15 at 14:54
  • 1
    You should tell us first. What _is_ wrong with that function? What is the expected result and what does it return instead? – Sebastian Simon Sep 15 '15 at 14:55
  • This function looks like it attempts to capitalize the first character of every word. – Halcyon Sep 15 '15 at 14:56
  • 5
    Like the title says, I am trying to capitalize the first letter of each word in the string. I don't appreciate the downvotes or the negativity on a forum that is supposed to be supportive in nature. @somethinghere - Thank you for your response. – slurrr Sep 15 '15 at 21:45
  • @slurr don't let it get to you too much, sometimes the people here can be a bit nitpicky about wording. Next time, try to be as precise as possible and you will probably receive a better response. Take it as a learning experience, so welcome to Stack Overflow and don't hold grudges (: – somethinghere Sep 15 '15 at 21:49
  • Possible duplicate of [Convert string to title case with JavaScript](https://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript) – faintsignal May 11 '18 at 04:26

47 Answers47

240

You are not assigning your changes to the array again, so all your efforts are in vain. Try this:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));
somethinghere
  • 16,311
  • 2
  • 28
  • 42
  • @Halcyon That would just result in one letter for each word. – epascarello Sep 15 '15 at 14:59
  • this is exactly what I am trying to accomplish, thank you for your time and patience – slurrr Sep 15 '15 at 21:57
  • @slurr no problem. If you think this answers your question, could you mark is as the answer? Good luck with all your future javascript endeavours (: – somethinghere Sep 15 '15 at 21:58
  • 44
    In es6, you can do this, which looks a bit nicer: ```myStr.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1)).join(' ');``` – Patrick Michaelsen Nov 08 '18 at 22:23
  • 1
    @PatrickMichaelsen Indeed you can. I won't change the answer though, its from 2015 and I know times have changed but I'll keep it up for posterity. Also, I wouldn't write it like this anymore either :) But feel free to post yours as your own answer I guess? – somethinghere Nov 09 '18 at 08:44
  • 3
    Yes, I agree, the current answer is fine. That's why I put it in the comments, simply for reference of newer visitors. – Patrick Michaelsen Nov 10 '18 at 09:13
  • 1
    I ran a benchmark of this function against 3 competitor functions and found it to be the most performant - less than 1/3 the execution time of the worst competitor (Chrome 73). http://jsben.ch/AkHgP – Michael Thompson Apr 17 '19 at 04:26
  • @MichaelThompson on mine (Safari 12) it was the third code block that was the fastest, but I believe this simply comes down to how big Regex is. If you need to use it multiple times it will slow down significantly. Still not bad for 4-year old code... (The first one was also fastest on my latest chrome, nice!) – somethinghere Apr 18 '19 at 11:56
  • If you hold 'shift' while typing the last letter is already caputalized ? – Shamseer Ahammed Jun 22 '21 at 07:42
  • @shamseerahammed Whats your point? Teaching people how to type is not teaching them programming logic, so saying ‘you’re using your keyboard wrong’ really doesn't help anyone? – somethinghere Jun 22 '21 at 13:33
187

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";
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
  • @epascarello I don't understand you, what are you telling me? – Marcos Pérez Gude Sep 15 '15 at 15:00
  • question is "What is wrong with this function?", else this would have been duplicate of http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript?rq=1 or http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript – Hacketo Sep 15 '15 at 15:04
  • @Hacketo I give OP a easy solution. if you think that question is duplicated, flag it. – Marcos Pérez Gude Sep 15 '15 at 15:25
  • Op ask for help to make his function work as expected, I think css is not helping him to understand witch mistakes he did. Not a duplicate then. Your answer is not easy solution, it's off topic. – Hacketo Sep 15 '15 at 15:29
  • 6
    thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude – slurrr Sep 15 '15 at 21:47
  • 1
    Yeah, it's real versatile – Marcos Pérez Gude Nov 30 '17 at 14:35
  • 15
    this is a "display only" change, the string itself is not changed. There's no reason to **ass**ume that the intended output is an HTML element - there's no indication that the code in the question is even in a browser! – Jaromanda X Dec 01 '17 at 01:54
  • 3
    Unfortunately in some cases if the value is 20mm and you use capitalize it will be 20Mm. Some cases javascript might be the only method. – GeorgeButter May 08 '20 at 07:02
  • 1
    As others have stated the question wasn't how to display capitalised text, but instead "converting the string to title case" – esp Mar 04 '21 at 04:00
  • It was smart to point out the use CSS. Thanks – Amir Nov 09 '22 at 14:38
  • This does not answer the question. JavaScript is used in many places where CSS is not applicable. Sometimes, one just needs to manipulate a string in JS. – Derek Henderson Feb 17 '23 at 19:00
143

ECMAScript 6 version:

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steve Brush
  • 2,911
  • 1
  • 23
  • 15
  • 2
    I also think you are missing, `toLowerCase()` on the very beginning, just in case the user or string is mixed case. – ArchNoob Jun 05 '18 at 00:26
  • In this case, you will convert all non single space " " to single space " " – Mahesh Jun 11 '21 at 19:03
117

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

Example usage:

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

console.log(toTitleCase("heLLo worLd"));
chickens
  • 19,976
  • 6
  • 58
  • 55
  • 2
    This is awsome! RegEx are the best. Can yo uelaborate more on what this part does? `m => m.toUpperCase()` – marcin2x4 Jul 18 '20 at 16:34
  • 2
    @marcin2x4 `m` matches the first character, so it makes first character uppercase. – chickens Oct 09 '20 at 04:08
  • It doesn't uppercase words like **şalk**. – AbsoluteBeginner Feb 26 '21 at 10:06
  • @AbsoluteBeginner you will need to replace toUpperCase and toLowerCase with a locale sensitive function like toLocaleUpperCase and toLocaleLowerCase – chickens Feb 27 '21 at 22:23
  • This solution also retains the whitespace between the words Input -> hello-----world $$$ Other solution -> Hello-World $$$ This solution -> Hello-----World – Mahesh Jun 11 '21 at 19:09
  • it doesn't work if the first string character starts with **ñ** – Lion Smith Jul 11 '22 at 06:20
  • This is good, but to add to this: `str.toLowerCase().replace(/(^\w|\s\w)/g, firstLetter => firstLetter.toUpperCase());` will ensure that all other letters are lower-cased first so that `hElLo WoRLD` becomes `Hello World` instead of `HElLo WoRLD`. – aprilmintacpineda Feb 17 '23 at 10:15
61

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

var str = text.toLowerCase().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
Nimer Awad
  • 3,967
  • 3
  • 17
  • 31
37

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

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

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

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

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

_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
waqas
  • 4,357
  • 3
  • 34
  • 42
23

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(' ')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anshuman Singh
  • 1,134
  • 1
  • 13
  • 21
  • 5
    Nice! You can use `w[0]` to make it even shorter.. Unlike regex it is easily extendable by ANY symbol but not only `space`. By any I mean `(` `[` `"`, because letters should be capitalized after these symbols as well. So thanks for your solution! – Systems Rebooter Dec 19 '19 at 20:36
  • This is golden! – amarinediary Jun 30 '21 at 09:11
14

ECMAScript 6 version:

title
    .split(/ /g).map(word =>
        `${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
    .join(" ");
timelfelt
  • 680
  • 1
  • 11
  • 26
Arthur Clemens
  • 2,848
  • 24
  • 18
  • 6
    I only saw this now and it's pretty neat, but I think you need to join using a `" "` instead of `""`, otherwise you will get one big word, no? – somethinghere Feb 01 '17 at 09:18
10
text-transform: capitalize;

CSS has got it :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Charlie OConor
  • 857
  • 1
  • 9
  • 18
  • This question is about transforming a string in JS, not how to display it with CSS. One shouldn't assume this is used in an environment where CSS is applicable. – Derek Henderson Feb 17 '23 at 19:08
  • It took 4 years to find someone who didn't get the joke! There are at least five correct responses of how to do it correctly in js itself. The point was to show was to make the reader think outside of the strict confines of how to do X in JS. The point was to show features of CSS that many readers might not be aware of and help them think outside the box. – Charlie OConor Feb 19 '23 at 21:36
9

-

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.


<textarea id="input" type="text">I'm a little tea pot</textarea><br /><br />
<textarea id="output" type="text" readonly=""></textarea>
<script>
(function(){
    "use strict"
    var fromCode = String.fromCharCode;
    function upper(x){return x[0]==="'"?x:fromCode(x.charCodeAt(0) ^ 32)}
    (input.oninput = function(){
      output.value = input.value.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, upper);
    })();
})();
</script>
Jack G
  • 4,553
  • 2
  • 41
  • 50
  • You forgot to add return to your function as in: function autoCaps(string){ return string.replace(/\b[a-z]|\B[A-Z]/g, function(x){ return String.fromCharCode(x.charCodeAt(0)^32); }); } – Archy Aug 07 '18 at 06:17
  • @Archy Thank you for your correction. I have made the change you proposed. – Jack G Apr 25 '19 at 19:15
7

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(" ");
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

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";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pat
  • 145
  • 2
  • 11
5

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);
};
Linh Nguyen
  • 59
  • 1
  • 1
  • This capitalizes the first letter of only the 1st word of the string. The OP is asking about capitalizing each word! – user7607751 Feb 07 '22 at 16:32
5

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

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

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");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ntnbst
  • 59
  • 7
4
function LetterCapitalize(str) { 
  return str.split(" ").map(item=>item.substring(0,1).toUpperCase()+item.substring(1)).join(" ")
}
Alex Varghese
  • 2,000
  • 16
  • 17
4

let cap = (str) => {
  let arr = str.split(' ');
  arr.forEach(function(item, index) {
    arr[index] = item.replace(item[0], item[0].toUpperCase());
  });

  return arr.join(' ');
};

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

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

adiga
  • 34,372
  • 9
  • 61
  • 83
starWave
  • 251
  • 2
  • 3
4

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')
Anthony Awuley
  • 3,455
  • 30
  • 20
  • Shouldn't the word.slice(1) be replaced with word.slice(1).toLowerCase() to make sure the rest is not capitalized (just in case it was in the original sentence) ? – Anton Krug Jan 03 '20 at 16:44
4

Here a simple one-liner

const ucFirst = t => t.replace(/(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g, c => c.toUpperCase());

Note that it only changes case of first letter of every word, you might want to use it as so:

console.log(ucFirst('foO bAr'));
// FoO BAr

console.log(ucFirst('foO bAr'.toLowerCase()));
// Foo Bar

// works with accents too
console.log(ucFirst('éfoO bAr'));
// ÉfoO BAr

Or based on String.prototype here is one that handles several modes:

String.prototype.ucFirst = function (mode = 'eachWord') {
  const modes = {
    eachWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g,
    firstWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/,
    firstChar: /^[A-Za-zÀ-ÖØ-öø-ÿ]/,
    firstLetter: /[A-Za-zÀ-ÖØ-öø-ÿ]/,
  };

  if (mode in modes) {
    return this.replace(modes[mode], c => c.toUpperCase());
  } else {
    throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: ` + Object.keys(modes).join('|');
  }
};

console.log('eachWord', 'foO bAr'.ucFirst());
// FoO BAr

console.log('eachWord', 'foO bAr'.toLowerCase().ucFirst());
// Foo Bar

console.log('firstWord', '1foO bAr'.ucFirst('firstWord'));
// 1foO BAr

console.log('firstChar', '1foO bAr'.ucFirst('firstChar'));
// 1foO bAr

console.log('firstLetter', '1foO bAr'.ucFirst('firstLetter'));
// 1FoO bAr

Edit:

Or based on String.prototype one that handles several modes and an optional second argument to specify word separators (String or RegExp):

String.prototype.ucFirst = function (mode = 'eachWord', wordSeparator = /\s/) {
  const letters = /[A-Za-zÀ-ÖØ-öø-ÿ]/;
  const ws =
    '^|' +
    (wordSeparator instanceof RegExp
      ? '(' + wordSeparator.source + ')'
      : // sanitize string for RegExp https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex#comment52837041_6969486
        '[' + wordSeparator.replace(/[[{}()*+?^$|\]\.\\]/g, '\\$&') + ']');

  const r =
    mode === 'firstLetter'
      ? letters
      : mode === 'firstChar'
      ? new RegExp('^' + letters.source)
      : mode === 'firstWord' || mode === 'eachWord'
      ? new RegExp(
          '(' + ws + ')' + letters.source,
          mode === 'eachWord' ? 'g' : undefined
        )
      : undefined;

  if (r) {
    return this.replace(r, (c) => c.toUpperCase());
  } else {
    throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: firstLetter|firstChar|firstWord|eachWord`;
  }
};

console.log("mike o'hara".ucFirst('eachWord', " \t\r\n\f\v'"));
// Mike O'Hara
console.log("mike o'hara".ucFirst('eachWord', /[\s']/));
// Mike O'Hara

Antony Gibbs
  • 1,321
  • 14
  • 24
4

With Regex and handling special characters like ñ with multiple spaces in between : /(^.|\s+.)/g

let text = "ñora    ñora"
console.log(text.toLowerCase().replace(/(^.|\s+.)/g, m => m.toUpperCase()))
Thomas
  • 410
  • 9
  • 14
3
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(' ');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
thiagorls
  • 61
  • 4
3

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
iolsmit
  • 383
  • 2
  • 13
3

TypeScript fat arrow FTW

export const formatTitleCase = (string: string) =>
    string
        .toLowerCase()
        .split(" ")
        .map((word) => word.charAt(0).toUpperCase() + word.substring(1))
        .join(" ");
3

There are many ways for achieving this, for instance you can try looping over string, or use JavaScript built in split(), map() and join()

I prefer using regex with replace method which is available on string

capitalize = (str) =>  {
  return str.replace(/\b[a-z]/g, (letter) => letter.toUpperCase(););
}
  • identified using the \b boundary matcher and the [a-z] character class, and replaces it with the uppercase version of the letter using a callback function.

  • more efficient because it only iterates over the characters in the string once, and it uses a regular expression to identify the letters to be capitalized, which is generally faster than implementing the same logic using loops and string manipulation.

Hanzla Habib
  • 3,457
  • 25
  • 25
2

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

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"));
Dag Sondre Hansen
  • 2,449
  • 20
  • 22
2

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.

function titleCase(text) {
  if (!text) return text;
  if (typeof text !== 'string') throw "invalid argument";

  return text.toLowerCase().split(' ').map(value => {
    return value.charAt(0).toUpperCase() + value.substring(1);
  }).join(' ');
}

console.log(titleCase("I'm A little tea pot"));
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
2

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());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TayabRaza
  • 51
  • 4
2

This is a perfect example of using modern javascript practices to improve readability. Have not yet seen a reduce version here, but this is what i use. Its both a curried one-liner and very readable

sentence
    .trim().toLowerCase()
    .split(' ')
    .reduce((sentence, word) => `${sentence} ${word[0].toUpperCase()}${word.substring(1)}`, '')
    .trim()
Rutger
  • 131
  • 1
  • 4
2

If practical, do make use of the text-transform: capitalize; CSS property to convert the text to title case.

It is less expensive an operation compared to the JavaScript option in situations were you could equally rely on CSS to achieve the same result.

I'm A Little Tea Pot is the result of the snippet below.

<p style="text-transform: capitalize;">I'm a little tea pot</p>
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
1

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');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chris
  • 11
  • 3
1

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")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eli Johnson
  • 1,492
  • 1
  • 10
  • 10
1

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));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alok Deshwal
  • 1,128
  • 9
  • 20
  • Why do you amend the String.prototype every time this method is called? If anything you need to do it _once_, and preferably you _never_ touch the prototypes of built-ins. It's a bit of a no-no... – somethinghere Jul 01 '20 at 18:00
1
var str = "hello world"
var result = str.split(" ").map(element => {
    return element[0].toUpperCase() + element.slice(1);
});
result = result.join(" ")
console.log(result);
Surbhi Dighe
  • 743
  • 5
  • 10
  • 3
    While not exactly a duplicate of existing answers, I don't think that this answer really adds anything that other answers do not already cover. If you disagree, please [edit] and explain. – General Grievance Feb 21 '22 at 17:25
1

You can build upon this inputString[0].toUpperCase() + inputString.slice(1).toLowerCase() :)

0
/* 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");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

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);
Pang
  • 9,564
  • 146
  • 81
  • 122
  • 2
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/350567) by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – iBug Jan 10 '18 at 03:55
0

As of ECMA2017 or ES8

const titleCase = (string) => {
  return string
    .split(' ')
    .map(word => word.substr(0,1).toUpperCase() + word.substr(1,word.length))
    .join(' ');
};

let result = titleCase('test test test');
console.log(result);

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.
Pulkit Aggarwal
  • 2,554
  • 4
  • 23
  • 33
  • I think you are missing something in the very beginning before splitting and that is `toLowerCase()`. – ArchNoob Jun 05 '18 at 00:25
  • @ArchNoob, yes we can add toLowerCase() before split. But its totally depend on use case such as if we want "TeSt Test" output for "teSt test" input, in this case, we can't add toLowerCase(). – Pulkit Aggarwal Jun 05 '18 at 03:41
0

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

  return upperCaseString;
}

titleCase("hello woRLD");
Hamza Dahmoun
  • 1,204
  • 10
  • 16
0

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

Abhishek Kumar
  • 820
  • 10
  • 18
0

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aathi
  • 2,599
  • 2
  • 19
  • 16
0

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();});
}
Ankit Virani
  • 125
  • 1
  • 13
0
let string = "I'm a little tea pot";

Now, create a function that will take a string as an argument.

function titleCase(str) {
   return str.split(" ").map(s => s.charAt(0).toUpperCase() + s.substr(1).toLowerCase()).join(" ")
} 

Output

titleCase(string); // "I'm A Little Tea Pot"
Kapilrc
  • 1,362
  • 15
  • 11
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Mar 05 '21 at 14:59
  • Thanks @MarkRotteveel! I have tried to provide an explanation. – Kapilrc Mar 05 '21 at 17:01
0

You could do it is simple way like this in one line with map with toUpperCase:

    text.split(' ').map(w => { let t = w.split(''); t[0] = t[0].toUpperCase(); return t.join('') }).join(' ')
  • Yes, that's my fault, I fix my answer and just did changes in that way: text.split(' ').map(w => { let t = w.split(''); t[0] = t[0].toUpperCase(); return t.join('') }).join(' ') – Andrew Zagarichuk Apr 10 '21 at 23:06
0

I have done this using this code below, hope it will help you:

<p id="p1">This is a paragraph.</p>

<script>
   const capitalize = (mySentence) => {
      const words = mySentence.split(" ");
      for (let i = 0; i < words.length; i++) {
         words[i] = words[i][0].toUpperCase() + words[i].substr(1);
      }
      return words.join(" ");
   };  
   const result = capitalize('This is a sample text');
   document.getElementById("p1").innerHTML = result;
</script>
Hammad Ahmad
  • 184
  • 1
  • 6
0

Try This Function:

const capitializeName = (name) => {
 
     const splitName = name.split(' ');
        const namesUpper = [];

    for (const n of splitName) {
        namesUpper.push(n[0].toUpperCase() + n.slice(1));
    }
    console.log(namesUpper.join(' '));
};

capitializeName('jahid bhuiyan');
General Grievance
  • 4,555
  • 31
  • 31
  • 45
0

Capitalize each word in a string with odd separator characters (fast solution without regex)

function capitalizeFirstLetter(str) {
  function isLetter(char) {
    const code = char.charCodeAt(0);
    // Considering apostrophe (char code 39) as a letter
    return code > 64 && code < 91 || code > 96 && code < 123 || char.charCodeAt(0) === 39;
  }

  str = str.toLowerCase();

  let newStr = '';
  let processingWord = false;

  for (let i = 0; i < str.length; i += 1) {
    if (!processingWord && isLetter(str[i])) {
      processingWord = true;
      newStr += str[i].toUpperCase();
    }
    else {
      newStr += str[i];
    }

    if (processingWord && !isLetter(str[i])) {
      processingWord = false;
    }
  }

  return newStr;
}

// stack overflow -> Stack Overflow
// ping-pong -> Ping-Pong
// domino's pizza -> Domino's Pizza
// /some/path -> /Some/Path

Maciej Krawczyk
  • 14,825
  • 5
  • 55
  • 67
0

You can capitalize the first letter of a string in JavaScript by using some simple string and array functions. Here’s the complete code sample, followed by an explanation of how it works:

const greeting = "hello"
const capitalize = string => [
  ...string.slice(0, 1).toUpperCase(),
  ...string.slice(1)
].join("")

// Here's the same function, rewritten in long-form JavaScript
const capitalize = function(string) {
  return [
    ...string.slice(0, 1).toUpperCase(),
    ...string.slice(1)
  ].join("")
}

capitalize(greeting) // "Hello"

How it works — slices and spreads

This works by using slice to split the string by characters into two sections: the first character—using .slice(0, 1)—and the remainder of the string, with .slice(1). Without a second argument provided to slice, it will grab the rest of the string.

Strings can be coerced into arrays in JavaScript using the ES6 spread operator. By spreading the string into two sections, and calling .toUpperCase() on the first character, we can effectively capitalize the first letter of the string, and then join it back together inside of an array of characters. For instance:

const greeting = "hello"
const capitalizeWithoutJoin = string => [  
  ...string.slice(0, 1).toUpperCase(),
  ...string.slice(1)
]

capitalizeWithoutJoin(greeting) // ["H", "e", "l", "l", "o"]

The spread operator takes both strings, and combines the array of characters from each into a single array, which is returned by the function. The original capitalize function takes that array of characters, and joins them back into a string.

Capitalize multiple words in a sentence

The advantage of capitalizing the first letter of a string in this way is that you can re-use it for multiple words. For instance, if you want to capitalize the first letter of every word in a larger string, you can map through the words and call capitalize on each:

// const capitalize = string ...
const long_string = "hello world how is it going"
const capitalized = long_string.split(" ").map(string => capitalize(string)).join(" ")  

capitalized // "Hello World How Is It Going"

(Originally posted on my blog: https://7.dev/javascript-capitalize-first-letter/)

Kristian
  • 1,351
  • 1
  • 14
  • 20