Capitalize First Letter of each word in a String - JavaScript












19















What is wrong with this function? I am lost thanks for help.



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;
}

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









share|improve this question

























  • 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








  • 1





    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?

    – Xufox
    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











  • 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
















19















What is wrong with this function? I am lost thanks for help.



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;
}

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









share|improve this question

























  • 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








  • 1





    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?

    – Xufox
    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











  • 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














19












19








19


6






What is wrong with this function? I am lost thanks for help.



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;
}

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









share|improve this question
















What is wrong with this function? I am lost thanks for help.



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;
}

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






javascript string capitalize charat






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 15 '15 at 15:32









SNag

10.7k93853




10.7k93853










asked Sep 15 '15 at 14:52









slurrrslurrr

133117




133117













  • 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








  • 1





    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?

    – Xufox
    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











  • 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



















  • 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








  • 1





    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?

    – Xufox
    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











  • 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

















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







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






1




1





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







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




1





You should tell us first. What is wrong with that function? What is the expected result and what does it return instead?

– Xufox
Sep 15 '15 at 14:55





You should tell us first. What is wrong with that function? What is the expected result and what does it return instead?

– Xufox
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





This function looks like it attempts to capitalize the first character of every word.

– Halcyon
Sep 15 '15 at 14:56













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





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












19 Answers
19






active

oldest

votes


















53














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








share|improve this answer


























  • @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











  • this is NOT working for things in quotes.

    – Yevgeniy Afanasyev
    Nov 30 '17 at 3:15






  • 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 9 '18 at 8:44



















28














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





share|improve this answer
























  • @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 stackoverflow.com/questions/1026069/… or stackoverflow.com/questions/196972/…

    – Hacketo
    Sep 15 '15 at 15:04








  • 1





    thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude

    – slurrr
    Sep 15 '15 at 21:47






  • 2





    this solution saved my time

    – DirtyMind
    Mar 15 '17 at 18:55








  • 1





    this is also working for things in quotes.

    – Yevgeniy Afanasyev
    Nov 30 '17 at 3:15



















15














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








share|improve this answer


























  • this is NOT working for things in quotes.

    – Yevgeniy Afanasyev
    Nov 30 '17 at 3:16






  • 1





    I also think you are missing, toLowerCase() on the very beginning, just in case the user or string is mixed case.

    – ArchNoob
    Jun 5 '18 at 0:26



















9














If you can use thirdparty 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>








share|improve this answer































    3














    ES2015 version:



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





    share|improve this answer



















    • 2





      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 1 '17 at 9:18











    • this is NOT working for things in quotes.

      – Yevgeniy Afanasyev
      Nov 30 '17 at 3:17



















    2














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





    share|improve this answer
























    • this is NOT working for things in quotes.

      – Yevgeniy Afanasyev
      Nov 30 '17 at 3:17



















    2














    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 fastest and most memory efficient.



    'tHe VeRy LOOong StRINg'.replace(/b[a-z]|B[A-Z]/g, function(x){return String.fromCharCode(x.charCodeAt(0)^32)})


    Or, as a function:



    var autoCaps = (function(){
    var fromCharCode = String.fromCharCode;
    return function(string){
    string.replace(/b[a-z]|B[A-Z]/g, function(x){
    return fromCharCode(x.charCodeAt(0)^32);
    });
    }
    })();





    Demo






    <input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
    <input id="output" type="text" readonly />
    <script>
    (function(){
    var fromCharCode = String.fromCharCode;
    (input.oninput = function(){
    output.value = input.value.replace(
    /b[a-z]|B[A-Z]/g,
    function(x){return fromCharCode(x.charCodeAt(0)^32)}
    );
    })();
    })();
    </script>








    share|improve this answer


























    • 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 7 '18 at 6:17





















    1














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






    share|improve this answer
























    • you have some bugs, I fixed them here: jsfiddle.net/Eugene82/vm7ntudb

      – Yevgeniy Afanasyev
      Nov 30 '17 at 3:30



















    1














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





    share|improve this answer



















    • 1





      Add some comments to your answer.

      – HDJEMAI
      Dec 4 '16 at 4:38



















    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('js string exasd');





    share|improve this answer
























    • you should provide a bit more detail (what was the wrong?)

      – hering
      May 16 '17 at 12:51





















    1














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





    share|improve this answer
























    • I like this solution best,,, nice one

      – jidexl21
      Dec 17 '18 at 10:48



















    1














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





    share|improve this answer































      1














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








      share|improve this answer
























      • I like this the most.

        – Spock
        Jan 10 at 7:31



















      0














      /* 1. Transform your string into lower case
      2. Split your string into an array. Notice the white space i'm using for 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");





      share|improve this answer





















      • 2





        Add explanation to the code.

        – neophyte
        Feb 7 '17 at 0:37



















      0














      Used replace() with RegExp



      function titleCase(str) {

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


      console.log(newStr);

      }

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





      share|improve this answer

































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





        share|improve this answer





















        • 2





          Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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 3:55



















        0














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






        function titleCase(str) {
        return str.toLowerCase().split(' ').map(function(chunk){
        return chunk.charAt(0).toUpperCase() + chunk.substring(1);
        }).join(' ');
        }

        document.write(titleCase("I'm an even smaller tea pot"));








        share|improve this answer































          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.




          share|improve this answer
























          • I think you are missing something in the very beginning before splitting and that is toLowerCase().

            – ArchNoob
            Jun 5 '18 at 0: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 5 '18 at 3:41



















          -3














          isn't it better to make whole string a lowerCase and only first letter of it upper?



          function titleCase(str) {
          return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
          }





          share|improve this answer



















          • 2





            This Is A Title Case Sentence !== This is a title case sentence

            – Jaromanda X
            Sep 15 '15 at 15:00











          • @JaromandaX: OP's title says "Capitalize First Letter of a String", hence this answer. OP is confused.

            – SNag
            Sep 15 '15 at 15:19











          • @SNag each item of the array is a string

            – Hacketo
            Sep 15 '15 at 15:23











          • title is one thing, code looks like it's attempting to do title case ... the function is even called titleCase ... I'm going with the numbers

            – Jaromanda X
            Sep 15 '15 at 15:25











          • @JaromandaX: You're right. Fixed the title for OP.

            – SNag
            Sep 15 '15 at 15:32











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32589197%2fcapitalize-first-letter-of-each-word-in-a-string-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          19 Answers
          19






          active

          oldest

          votes








          19 Answers
          19






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          53














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








          share|improve this answer


























          • @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











          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15






          • 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 9 '18 at 8:44
















          53














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








          share|improve this answer


























          • @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











          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15






          • 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 9 '18 at 8:44














          53












          53








          53







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








          share|improve this answer















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








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





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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 28 '16 at 20:17









          Aaron Goldsmith

          348




          348










          answered Sep 15 '15 at 14:56









          somethingheresomethinghere

          10.5k11932




          10.5k11932













          • @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











          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15






          • 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 9 '18 at 8:44



















          • @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











          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15






          • 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 9 '18 at 8:44

















          @Halcyon That would just result in one letter for each word.

          – epascarello
          Sep 15 '15 at 14:59





          @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





          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





          @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













          this is NOT working for things in quotes.

          – Yevgeniy Afanasyev
          Nov 30 '17 at 3:15





          this is NOT working for things in quotes.

          – Yevgeniy Afanasyev
          Nov 30 '17 at 3:15




          1




          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 9 '18 at 8:44





          @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 9 '18 at 8:44













          28














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





          share|improve this answer
























          • @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 stackoverflow.com/questions/1026069/… or stackoverflow.com/questions/196972/…

            – Hacketo
            Sep 15 '15 at 15:04








          • 1





            thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude

            – slurrr
            Sep 15 '15 at 21:47






          • 2





            this solution saved my time

            – DirtyMind
            Mar 15 '17 at 18:55








          • 1





            this is also working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15
















          28














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





          share|improve this answer
























          • @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 stackoverflow.com/questions/1026069/… or stackoverflow.com/questions/196972/…

            – Hacketo
            Sep 15 '15 at 15:04








          • 1





            thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude

            – slurrr
            Sep 15 '15 at 21:47






          • 2





            this solution saved my time

            – DirtyMind
            Mar 15 '17 at 18:55








          • 1





            this is also working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15














          28












          28








          28







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





          share|improve this answer













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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 15 '15 at 14:55









          Marcos Pérez GudeMarcos Pérez Gude

          17.5k32451




          17.5k32451













          • @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 stackoverflow.com/questions/1026069/… or stackoverflow.com/questions/196972/…

            – Hacketo
            Sep 15 '15 at 15:04








          • 1





            thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude

            – slurrr
            Sep 15 '15 at 21:47






          • 2





            this solution saved my time

            – DirtyMind
            Mar 15 '17 at 18:55








          • 1





            this is also working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15



















          • @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 stackoverflow.com/questions/1026069/… or stackoverflow.com/questions/196972/…

            – Hacketo
            Sep 15 '15 at 15:04








          • 1





            thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude

            – slurrr
            Sep 15 '15 at 21:47






          • 2





            this solution saved my time

            – DirtyMind
            Mar 15 '17 at 18:55








          • 1





            this is also working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:15

















          @epascarello I don't understand you, what are you telling me?

          – Marcos Pérez Gude
          Sep 15 '15 at 15:00





          @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 stackoverflow.com/questions/1026069/… or stackoverflow.com/questions/196972/…

          – Hacketo
          Sep 15 '15 at 15:04







          question is "What is wrong with this function?", else this would have been duplicate of stackoverflow.com/questions/1026069/… or stackoverflow.com/questions/196972/…

          – Hacketo
          Sep 15 '15 at 15:04






          1




          1





          thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude

          – slurrr
          Sep 15 '15 at 21:47





          thanks for the reply, but I am trying to do this using javascript for practice @MarcosPérezGude

          – slurrr
          Sep 15 '15 at 21:47




          2




          2





          this solution saved my time

          – DirtyMind
          Mar 15 '17 at 18:55







          this solution saved my time

          – DirtyMind
          Mar 15 '17 at 18:55






          1




          1





          this is also working for things in quotes.

          – Yevgeniy Afanasyev
          Nov 30 '17 at 3:15





          this is also working for things in quotes.

          – Yevgeniy Afanasyev
          Nov 30 '17 at 3:15











          15














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








          share|improve this answer


























          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:16






          • 1





            I also think you are missing, toLowerCase() on the very beginning, just in case the user or string is mixed case.

            – ArchNoob
            Jun 5 '18 at 0:26
















          15














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








          share|improve this answer


























          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:16






          • 1





            I also think you are missing, toLowerCase() on the very beginning, just in case the user or string is mixed case.

            – ArchNoob
            Jun 5 '18 at 0:26














          15












          15








          15







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








          share|improve this answer















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








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





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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 26 '18 at 16:04

























          answered Apr 12 '17 at 18:24









          Steve BrushSteve Brush

          61878




          61878













          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:16






          • 1





            I also think you are missing, toLowerCase() on the very beginning, just in case the user or string is mixed case.

            – ArchNoob
            Jun 5 '18 at 0:26



















          • this is NOT working for things in quotes.

            – Yevgeniy Afanasyev
            Nov 30 '17 at 3:16






          • 1





            I also think you are missing, toLowerCase() on the very beginning, just in case the user or string is mixed case.

            – ArchNoob
            Jun 5 '18 at 0:26

















          this is NOT working for things in quotes.

          – Yevgeniy Afanasyev
          Nov 30 '17 at 3:16





          this is NOT working for things in quotes.

          – Yevgeniy Afanasyev
          Nov 30 '17 at 3:16




          1




          1





          I also think you are missing, toLowerCase() on the very beginning, just in case the user or string is mixed case.

          – ArchNoob
          Jun 5 '18 at 0:26





          I also think you are missing, toLowerCase() on the very beginning, just in case the user or string is mixed case.

          – ArchNoob
          Jun 5 '18 at 0:26











          9














          If you can use thirdparty 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>








          share|improve this answer




























            9














            If you can use thirdparty 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>








            share|improve this answer


























              9












              9








              9







              If you can use thirdparty 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>








              share|improve this answer













              If you can use thirdparty 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>








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





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






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 29 '16 at 11:23









              waqaswaqas

              2,29332436




              2,29332436























                  3














                  ES2015 version:



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





                  share|improve this answer



















                  • 2





                    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 1 '17 at 9:18











                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17
















                  3














                  ES2015 version:



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





                  share|improve this answer



















                  • 2





                    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 1 '17 at 9:18











                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17














                  3












                  3








                  3







                  ES2015 version:



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





                  share|improve this answer













                  ES2015 version:



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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 17 '16 at 15:43









                  Arthur ClemensArthur Clemens

                  1,9491716




                  1,9491716








                  • 2





                    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 1 '17 at 9:18











                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17














                  • 2





                    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 1 '17 at 9:18











                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17








                  2




                  2





                  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 1 '17 at 9:18





                  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 1 '17 at 9:18













                  this is NOT working for things in quotes.

                  – Yevgeniy Afanasyev
                  Nov 30 '17 at 3:17





                  this is NOT working for things in quotes.

                  – Yevgeniy Afanasyev
                  Nov 30 '17 at 3:17











                  2














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





                  share|improve this answer
























                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17
















                  2














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





                  share|improve this answer
























                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17














                  2












                  2








                  2







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





                  share|improve this answer













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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jun 27 '17 at 21:27









                  Cheyenne CrawfordCheyenne Crawford

                  311




                  311













                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17



















                  • this is NOT working for things in quotes.

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:17

















                  this is NOT working for things in quotes.

                  – Yevgeniy Afanasyev
                  Nov 30 '17 at 3:17





                  this is NOT working for things in quotes.

                  – Yevgeniy Afanasyev
                  Nov 30 '17 at 3:17











                  2














                  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 fastest and most memory efficient.



                  'tHe VeRy LOOong StRINg'.replace(/b[a-z]|B[A-Z]/g, function(x){return String.fromCharCode(x.charCodeAt(0)^32)})


                  Or, as a function:



                  var autoCaps = (function(){
                  var fromCharCode = String.fromCharCode;
                  return function(string){
                  string.replace(/b[a-z]|B[A-Z]/g, function(x){
                  return fromCharCode(x.charCodeAt(0)^32);
                  });
                  }
                  })();





                  Demo






                  <input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
                  <input id="output" type="text" readonly />
                  <script>
                  (function(){
                  var fromCharCode = String.fromCharCode;
                  (input.oninput = function(){
                  output.value = input.value.replace(
                  /b[a-z]|B[A-Z]/g,
                  function(x){return fromCharCode(x.charCodeAt(0)^32)}
                  );
                  })();
                  })();
                  </script>








                  share|improve this answer


























                  • 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 7 '18 at 6:17


















                  2














                  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 fastest and most memory efficient.



                  'tHe VeRy LOOong StRINg'.replace(/b[a-z]|B[A-Z]/g, function(x){return String.fromCharCode(x.charCodeAt(0)^32)})


                  Or, as a function:



                  var autoCaps = (function(){
                  var fromCharCode = String.fromCharCode;
                  return function(string){
                  string.replace(/b[a-z]|B[A-Z]/g, function(x){
                  return fromCharCode(x.charCodeAt(0)^32);
                  });
                  }
                  })();





                  Demo






                  <input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
                  <input id="output" type="text" readonly />
                  <script>
                  (function(){
                  var fromCharCode = String.fromCharCode;
                  (input.oninput = function(){
                  output.value = input.value.replace(
                  /b[a-z]|B[A-Z]/g,
                  function(x){return fromCharCode(x.charCodeAt(0)^32)}
                  );
                  })();
                  })();
                  </script>








                  share|improve this answer


























                  • 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 7 '18 at 6:17
















                  2












                  2








                  2







                  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 fastest and most memory efficient.



                  'tHe VeRy LOOong StRINg'.replace(/b[a-z]|B[A-Z]/g, function(x){return String.fromCharCode(x.charCodeAt(0)^32)})


                  Or, as a function:



                  var autoCaps = (function(){
                  var fromCharCode = String.fromCharCode;
                  return function(string){
                  string.replace(/b[a-z]|B[A-Z]/g, function(x){
                  return fromCharCode(x.charCodeAt(0)^32);
                  });
                  }
                  })();





                  Demo






                  <input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
                  <input id="output" type="text" readonly />
                  <script>
                  (function(){
                  var fromCharCode = String.fromCharCode;
                  (input.oninput = function(){
                  output.value = input.value.replace(
                  /b[a-z]|B[A-Z]/g,
                  function(x){return fromCharCode(x.charCodeAt(0)^32)}
                  );
                  })();
                  })();
                  </script>








                  share|improve this answer















                  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 fastest and most memory efficient.



                  'tHe VeRy LOOong StRINg'.replace(/b[a-z]|B[A-Z]/g, function(x){return String.fromCharCode(x.charCodeAt(0)^32)})


                  Or, as a function:



                  var autoCaps = (function(){
                  var fromCharCode = String.fromCharCode;
                  return function(string){
                  string.replace(/b[a-z]|B[A-Z]/g, function(x){
                  return fromCharCode(x.charCodeAt(0)^32);
                  });
                  }
                  })();





                  Demo






                  <input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
                  <input id="output" type="text" readonly />
                  <script>
                  (function(){
                  var fromCharCode = String.fromCharCode;
                  (input.oninput = function(){
                  output.value = input.value.replace(
                  /b[a-z]|B[A-Z]/g,
                  function(x){return fromCharCode(x.charCodeAt(0)^32)}
                  );
                  })();
                  })();
                  </script>








                  <input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
                  <input id="output" type="text" readonly />
                  <script>
                  (function(){
                  var fromCharCode = String.fromCharCode;
                  (input.oninput = function(){
                  output.value = input.value.replace(
                  /b[a-z]|B[A-Z]/g,
                  function(x){return fromCharCode(x.charCodeAt(0)^32)}
                  );
                  })();
                  })();
                  </script>





                  <input id="input" type="text" value="'tHe VeRy LOOong StRINg'" /><br /><br />
                  <input id="output" type="text" readonly />
                  <script>
                  (function(){
                  var fromCharCode = String.fromCharCode;
                  (input.oninput = function(){
                  output.value = input.value.replace(
                  /b[a-z]|B[A-Z]/g,
                  function(x){return fromCharCode(x.charCodeAt(0)^32)}
                  );
                  })();
                  })();
                  </script>






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Aug 12 '18 at 14:54

























                  answered Aug 10 '17 at 18:05









                  Jack GiffinJack Giffin

                  1,012925




                  1,012925













                  • 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 7 '18 at 6:17





















                  • 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 7 '18 at 6:17



















                  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 7 '18 at 6:17







                  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 7 '18 at 6:17













                  1














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






                  share|improve this answer
























                  • you have some bugs, I fixed them here: jsfiddle.net/Eugene82/vm7ntudb

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:30
















                  1














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






                  share|improve this answer
























                  • you have some bugs, I fixed them here: jsfiddle.net/Eugene82/vm7ntudb

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:30














                  1












                  1








                  1







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






                  share|improve this answer













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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 6 '16 at 23:47









                  PatPat

                  609




                  609













                  • you have some bugs, I fixed them here: jsfiddle.net/Eugene82/vm7ntudb

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:30



















                  • you have some bugs, I fixed them here: jsfiddle.net/Eugene82/vm7ntudb

                    – Yevgeniy Afanasyev
                    Nov 30 '17 at 3:30

















                  you have some bugs, I fixed them here: jsfiddle.net/Eugene82/vm7ntudb

                  – Yevgeniy Afanasyev
                  Nov 30 '17 at 3:30





                  you have some bugs, I fixed them here: jsfiddle.net/Eugene82/vm7ntudb

                  – Yevgeniy Afanasyev
                  Nov 30 '17 at 3:30











                  1














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





                  share|improve this answer



















                  • 1





                    Add some comments to your answer.

                    – HDJEMAI
                    Dec 4 '16 at 4:38
















                  1














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





                  share|improve this answer



















                  • 1





                    Add some comments to your answer.

                    – HDJEMAI
                    Dec 4 '16 at 4:38














                  1












                  1








                  1







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





                  share|improve this answer













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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 4 '16 at 4:25









                  thiagorlsthiagorls

                  284




                  284








                  • 1





                    Add some comments to your answer.

                    – HDJEMAI
                    Dec 4 '16 at 4:38














                  • 1





                    Add some comments to your answer.

                    – HDJEMAI
                    Dec 4 '16 at 4:38








                  1




                  1





                  Add some comments to your answer.

                  – HDJEMAI
                  Dec 4 '16 at 4:38





                  Add some comments to your answer.

                  – HDJEMAI
                  Dec 4 '16 at 4:38











                  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('js string exasd');





                  share|improve this answer
























                  • you should provide a bit more detail (what was the wrong?)

                    – hering
                    May 16 '17 at 12:51


















                  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('js string exasd');





                  share|improve this answer
























                  • you should provide a bit more detail (what was the wrong?)

                    – hering
                    May 16 '17 at 12:51
















                  1












                  1








                  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('js string exasd');





                  share|improve this answer













                  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('js string exasd');






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered May 16 '17 at 12:37









                  ChrisChris

                  113




                  113













                  • you should provide a bit more detail (what was the wrong?)

                    – hering
                    May 16 '17 at 12:51





















                  • you should provide a bit more detail (what was the wrong?)

                    – hering
                    May 16 '17 at 12:51



















                  you should provide a bit more detail (what was the wrong?)

                  – hering
                  May 16 '17 at 12:51







                  you should provide a bit more detail (what was the wrong?)

                  – hering
                  May 16 '17 at 12:51













                  1














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





                  share|improve this answer
























                  • I like this solution best,,, nice one

                    – jidexl21
                    Dec 17 '18 at 10:48
















                  1














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





                  share|improve this answer
























                  • I like this solution best,,, nice one

                    – jidexl21
                    Dec 17 '18 at 10:48














                  1












                  1








                  1







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





                  share|improve this answer













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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 22 '17 at 9:44









                  ntnbstntnbst

                  215




                  215













                  • I like this solution best,,, nice one

                    – jidexl21
                    Dec 17 '18 at 10:48



















                  • I like this solution best,,, nice one

                    – jidexl21
                    Dec 17 '18 at 10:48

















                  I like this solution best,,, nice one

                  – jidexl21
                  Dec 17 '18 at 10:48





                  I like this solution best,,, nice one

                  – jidexl21
                  Dec 17 '18 at 10:48











                  1














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





                  share|improve this answer




























                    1














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





                    share|improve this answer


























                      1












                      1








                      1







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





                      share|improve this answer













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






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Apr 26 '18 at 9:30









                      Linh NguyenLinh Nguyen

                      111




                      111























                          1














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








                          share|improve this answer
























                          • I like this the most.

                            – Spock
                            Jan 10 at 7:31
















                          1














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








                          share|improve this answer
























                          • I like this the most.

                            – Spock
                            Jan 10 at 7:31














                          1












                          1








                          1







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








                          share|improve this answer













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








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





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






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 13 '18 at 15:52









                          Hamzeen HameemHamzeen Hameem

                          7181017




                          7181017













                          • I like this the most.

                            – Spock
                            Jan 10 at 7:31



















                          • I like this the most.

                            – Spock
                            Jan 10 at 7:31

















                          I like this the most.

                          – Spock
                          Jan 10 at 7:31





                          I like this the most.

                          – Spock
                          Jan 10 at 7:31











                          0














                          /* 1. Transform your string into lower case
                          2. Split your string into an array. Notice the white space i'm using for 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");





                          share|improve this answer





















                          • 2





                            Add explanation to the code.

                            – neophyte
                            Feb 7 '17 at 0:37
















                          0














                          /* 1. Transform your string into lower case
                          2. Split your string into an array. Notice the white space i'm using for 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");





                          share|improve this answer





















                          • 2





                            Add explanation to the code.

                            – neophyte
                            Feb 7 '17 at 0:37














                          0












                          0








                          0







                          /* 1. Transform your string into lower case
                          2. Split your string into an array. Notice the white space i'm using for 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");





                          share|improve this answer















                          /* 1. Transform your string into lower case
                          2. Split your string into an array. Notice the white space i'm using for 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");






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Feb 7 '17 at 2:12

























                          answered Feb 7 '17 at 0:17









                          Israel CalderónIsrael Calderón

                          11




                          11








                          • 2





                            Add explanation to the code.

                            – neophyte
                            Feb 7 '17 at 0:37














                          • 2





                            Add explanation to the code.

                            – neophyte
                            Feb 7 '17 at 0:37








                          2




                          2





                          Add explanation to the code.

                          – neophyte
                          Feb 7 '17 at 0:37





                          Add explanation to the code.

                          – neophyte
                          Feb 7 '17 at 0:37











                          0














                          Used replace() with RegExp



                          function titleCase(str) {

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


                          console.log(newStr);

                          }

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





                          share|improve this answer






























                            0














                            Used replace() with RegExp



                            function titleCase(str) {

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


                            console.log(newStr);

                            }

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





                            share|improve this answer




























                              0












                              0








                              0







                              Used replace() with RegExp



                              function titleCase(str) {

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


                              console.log(newStr);

                              }

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





                              share|improve this answer















                              Used replace() with RegExp



                              function titleCase(str) {

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


                              console.log(newStr);

                              }

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






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 19 '17 at 8:50









                              Moritz

                              57.6k19131184




                              57.6k19131184










                              answered May 19 '17 at 8:28









                              Eli JohnsonEli Johnson

                              11




                              11























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





                                  share|improve this answer





















                                  • 2





                                    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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 3:55
















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





                                  share|improve this answer





















                                  • 2





                                    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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 3:55














                                  0












                                  0








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





                                  share|improve this answer















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






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jan 11 '18 at 10:20









                                  Pang

                                  6,8911663101




                                  6,8911663101










                                  answered Jan 10 '18 at 3:24









                                  Sunil KumarSunil Kumar

                                  11




                                  11








                                  • 2





                                    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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 3:55














                                  • 2





                                    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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 3:55








                                  2




                                  2





                                  Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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 3:55





                                  Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value 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 3:55











                                  0














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






                                  function titleCase(str) {
                                  return str.toLowerCase().split(' ').map(function(chunk){
                                  return chunk.charAt(0).toUpperCase() + chunk.substring(1);
                                  }).join(' ');
                                  }

                                  document.write(titleCase("I'm an even smaller tea pot"));








                                  share|improve this answer




























                                    0














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






                                    function titleCase(str) {
                                    return str.toLowerCase().split(' ').map(function(chunk){
                                    return chunk.charAt(0).toUpperCase() + chunk.substring(1);
                                    }).join(' ');
                                    }

                                    document.write(titleCase("I'm an even smaller tea pot"));








                                    share|improve this answer


























                                      0












                                      0








                                      0







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






                                      function titleCase(str) {
                                      return str.toLowerCase().split(' ').map(function(chunk){
                                      return chunk.charAt(0).toUpperCase() + chunk.substring(1);
                                      }).join(' ');
                                      }

                                      document.write(titleCase("I'm an even smaller tea pot"));








                                      share|improve this answer













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






                                      function titleCase(str) {
                                      return str.toLowerCase().split(' ').map(function(chunk){
                                      return chunk.charAt(0).toUpperCase() + chunk.substring(1);
                                      }).join(' ');
                                      }

                                      document.write(titleCase("I'm an even smaller tea pot"));








                                      function titleCase(str) {
                                      return str.toLowerCase().split(' ').map(function(chunk){
                                      return chunk.charAt(0).toUpperCase() + chunk.substring(1);
                                      }).join(' ');
                                      }

                                      document.write(titleCase("I'm an even smaller tea pot"));





                                      function titleCase(str) {
                                      return str.toLowerCase().split(' ').map(function(chunk){
                                      return chunk.charAt(0).toUpperCase() + chunk.substring(1);
                                      }).join(' ');
                                      }

                                      document.write(titleCase("I'm an even smaller tea pot"));






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Apr 26 '18 at 9:44









                                      Dag Sondre HansenDag Sondre Hansen

                                      1,8041319




                                      1,8041319























                                          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.




                                          share|improve this answer
























                                          • I think you are missing something in the very beginning before splitting and that is toLowerCase().

                                            – ArchNoob
                                            Jun 5 '18 at 0: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 5 '18 at 3:41
















                                          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.




                                          share|improve this answer
























                                          • I think you are missing something in the very beginning before splitting and that is toLowerCase().

                                            – ArchNoob
                                            Jun 5 '18 at 0: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 5 '18 at 3:41














                                          0












                                          0








                                          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.




                                          share|improve this answer













                                          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.




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





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






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered May 16 '18 at 11:30









                                          Pulkit AggarwalPulkit Aggarwal

                                          99811420




                                          99811420













                                          • I think you are missing something in the very beginning before splitting and that is toLowerCase().

                                            – ArchNoob
                                            Jun 5 '18 at 0: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 5 '18 at 3:41



















                                          • I think you are missing something in the very beginning before splitting and that is toLowerCase().

                                            – ArchNoob
                                            Jun 5 '18 at 0: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 5 '18 at 3:41

















                                          I think you are missing something in the very beginning before splitting and that is toLowerCase().

                                          – ArchNoob
                                          Jun 5 '18 at 0:25





                                          I think you are missing something in the very beginning before splitting and that is toLowerCase().

                                          – ArchNoob
                                          Jun 5 '18 at 0: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 5 '18 at 3:41





                                          @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 5 '18 at 3:41











                                          -3














                                          isn't it better to make whole string a lowerCase and only first letter of it upper?



                                          function titleCase(str) {
                                          return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
                                          }





                                          share|improve this answer



















                                          • 2





                                            This Is A Title Case Sentence !== This is a title case sentence

                                            – Jaromanda X
                                            Sep 15 '15 at 15:00











                                          • @JaromandaX: OP's title says "Capitalize First Letter of a String", hence this answer. OP is confused.

                                            – SNag
                                            Sep 15 '15 at 15:19











                                          • @SNag each item of the array is a string

                                            – Hacketo
                                            Sep 15 '15 at 15:23











                                          • title is one thing, code looks like it's attempting to do title case ... the function is even called titleCase ... I'm going with the numbers

                                            – Jaromanda X
                                            Sep 15 '15 at 15:25











                                          • @JaromandaX: You're right. Fixed the title for OP.

                                            – SNag
                                            Sep 15 '15 at 15:32
















                                          -3














                                          isn't it better to make whole string a lowerCase and only first letter of it upper?



                                          function titleCase(str) {
                                          return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
                                          }





                                          share|improve this answer



















                                          • 2





                                            This Is A Title Case Sentence !== This is a title case sentence

                                            – Jaromanda X
                                            Sep 15 '15 at 15:00











                                          • @JaromandaX: OP's title says "Capitalize First Letter of a String", hence this answer. OP is confused.

                                            – SNag
                                            Sep 15 '15 at 15:19











                                          • @SNag each item of the array is a string

                                            – Hacketo
                                            Sep 15 '15 at 15:23











                                          • title is one thing, code looks like it's attempting to do title case ... the function is even called titleCase ... I'm going with the numbers

                                            – Jaromanda X
                                            Sep 15 '15 at 15:25











                                          • @JaromandaX: You're right. Fixed the title for OP.

                                            – SNag
                                            Sep 15 '15 at 15:32














                                          -3












                                          -3








                                          -3







                                          isn't it better to make whole string a lowerCase and only first letter of it upper?



                                          function titleCase(str) {
                                          return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
                                          }





                                          share|improve this answer













                                          isn't it better to make whole string a lowerCase and only first letter of it upper?



                                          function titleCase(str) {
                                          return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase();
                                          }






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Sep 15 '15 at 14:57









                                          AndretAndret

                                          127214




                                          127214








                                          • 2





                                            This Is A Title Case Sentence !== This is a title case sentence

                                            – Jaromanda X
                                            Sep 15 '15 at 15:00











                                          • @JaromandaX: OP's title says "Capitalize First Letter of a String", hence this answer. OP is confused.

                                            – SNag
                                            Sep 15 '15 at 15:19











                                          • @SNag each item of the array is a string

                                            – Hacketo
                                            Sep 15 '15 at 15:23











                                          • title is one thing, code looks like it's attempting to do title case ... the function is even called titleCase ... I'm going with the numbers

                                            – Jaromanda X
                                            Sep 15 '15 at 15:25











                                          • @JaromandaX: You're right. Fixed the title for OP.

                                            – SNag
                                            Sep 15 '15 at 15:32














                                          • 2





                                            This Is A Title Case Sentence !== This is a title case sentence

                                            – Jaromanda X
                                            Sep 15 '15 at 15:00











                                          • @JaromandaX: OP's title says "Capitalize First Letter of a String", hence this answer. OP is confused.

                                            – SNag
                                            Sep 15 '15 at 15:19











                                          • @SNag each item of the array is a string

                                            – Hacketo
                                            Sep 15 '15 at 15:23











                                          • title is one thing, code looks like it's attempting to do title case ... the function is even called titleCase ... I'm going with the numbers

                                            – Jaromanda X
                                            Sep 15 '15 at 15:25











                                          • @JaromandaX: You're right. Fixed the title for OP.

                                            – SNag
                                            Sep 15 '15 at 15:32








                                          2




                                          2





                                          This Is A Title Case Sentence !== This is a title case sentence

                                          – Jaromanda X
                                          Sep 15 '15 at 15:00





                                          This Is A Title Case Sentence !== This is a title case sentence

                                          – Jaromanda X
                                          Sep 15 '15 at 15:00













                                          @JaromandaX: OP's title says "Capitalize First Letter of a String", hence this answer. OP is confused.

                                          – SNag
                                          Sep 15 '15 at 15:19





                                          @JaromandaX: OP's title says "Capitalize First Letter of a String", hence this answer. OP is confused.

                                          – SNag
                                          Sep 15 '15 at 15:19













                                          @SNag each item of the array is a string

                                          – Hacketo
                                          Sep 15 '15 at 15:23





                                          @SNag each item of the array is a string

                                          – Hacketo
                                          Sep 15 '15 at 15:23













                                          title is one thing, code looks like it's attempting to do title case ... the function is even called titleCase ... I'm going with the numbers

                                          – Jaromanda X
                                          Sep 15 '15 at 15:25





                                          title is one thing, code looks like it's attempting to do title case ... the function is even called titleCase ... I'm going with the numbers

                                          – Jaromanda X
                                          Sep 15 '15 at 15:25













                                          @JaromandaX: You're right. Fixed the title for OP.

                                          – SNag
                                          Sep 15 '15 at 15:32





                                          @JaromandaX: You're right. Fixed the title for OP.

                                          – SNag
                                          Sep 15 '15 at 15:32


















                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32589197%2fcapitalize-first-letter-of-each-word-in-a-string-javascript%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Bressuire

                                          Vorschmack

                                          Quarantine