Capitalizing first letter of every word, doesn't work as expectedHow do I make the first letter of a string uppercase in JavaScript?How to capitalize first letter of each word, like a 2-word city?Capitalize the first letter of every wordJavascript time function to spell a word letter by letterCapitalize the first letter of string in AngularJsonChange in React doesn't capture the last character of textRegex get the middle section of each word javascriptLingo letters not working sometimesDon't understand why replace() method is not working as expectedCapitalizing the first letter of every word

Music Theory: Facts or Hierarchy of Opinions?

How does Asimov's second law deal with contradictory orders from different people?

Why was the Lobbying Transparency and Accountability Act of 2006 deemed too weak?

Adding a (stair/baby) gate without facing walls

Stationing Callouts using VBScript Labeling in ArcMap?

Word for soundtrack music which is part of the action of the movie

Correct word for a little toy that always stands up?

What is the term for completing a climbing route uncleanly?

Why don't short runways use ramps for takeoff?

What parameters are to be considered when choosing a MOSFET?

Can birds evolve without trees?

Why is “deal 6 damage” a legit phrase?

What does 「ちんちんかいかい」 mean?

Derivative is just speed of change?

Is it unprofessional to mention your cover letter and resume are best viewed in Chrome?

How do discovery writers hibernate?

Move arrows along a contour

Password management for kids - what's a good way to start?

Why didn't General Martok receive discommendation in Star Trek: Deep Space Nine?

Applications of pure mathematics in operations research

Can I use log and without any transformation variables in the one model for the independent variables?

Can machine learning learn a function like finding maximum from a list?

The grades of the students in a class

Russian pronunciation of /etc (a directory)



Capitalizing first letter of every word, doesn't work as expected


How do I make the first letter of a string uppercase in JavaScript?How to capitalize first letter of each word, like a 2-word city?Capitalize the first letter of every wordJavascript time function to spell a word letter by letterCapitalize the first letter of string in AngularJsonChange in React doesn't capture the last character of textRegex get the middle section of each word javascriptLingo letters not working sometimesDon't understand why replace() method is not working as expectedCapitalizing the first letter of every word






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















First of all I know that it is not the right way of doing it, but I want to understand why it is happening so I'll better understand the language.



function titleCase(str) 
let str1 = str.toLowerCase();
str1 = str1.replace(str1[0], str1[0].toUpperCase());
console.log(str1);

for(let i=1; i < str1.length; i++)
if(str1[i]===' ')
str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());
console.log(i);
console.log(str1);


return str1;


titleCase("ab cd ef gh ba");


So, if the first letter of the last word doesn't appear as second to last letter in any word before it is working, "ab cd ef gh" no problem here, but "ab cd ef gh ba" results in the following output: "AB Cd Ef Gh ba" etc..
Thanks!










share|improve this question


























  • The logic of your function is not correct. You need to reconsider it.

    – AhmadWabbi
    Mar 26 at 22:44











  • For the record, this function would be much better as: titleCase = str => str.replace(/b[a-z]/, x=>x.toUpperCase());

    – Niet the Dark Absol
    Mar 26 at 22:45











  • I'd say replace doesn't do what you think it does. It doesn't take an index, it takes a string value (or single character), and replace its first occurrence.

    – Bergi
    Mar 26 at 22:46












  • I assume this is what you were alluding to when you mentioned that you know this is not the right way of doing it, but just on the off-chance that it wasn't: python has an easy way to do this: docs.python.org/3/library/stdtypes.html#str.title

    – Kevin Wang
    Mar 26 at 22:50

















3















First of all I know that it is not the right way of doing it, but I want to understand why it is happening so I'll better understand the language.



function titleCase(str) 
let str1 = str.toLowerCase();
str1 = str1.replace(str1[0], str1[0].toUpperCase());
console.log(str1);

for(let i=1; i < str1.length; i++)
if(str1[i]===' ')
str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());
console.log(i);
console.log(str1);


return str1;


titleCase("ab cd ef gh ba");


So, if the first letter of the last word doesn't appear as second to last letter in any word before it is working, "ab cd ef gh" no problem here, but "ab cd ef gh ba" results in the following output: "AB Cd Ef Gh ba" etc..
Thanks!










share|improve this question


























  • The logic of your function is not correct. You need to reconsider it.

    – AhmadWabbi
    Mar 26 at 22:44











  • For the record, this function would be much better as: titleCase = str => str.replace(/b[a-z]/, x=>x.toUpperCase());

    – Niet the Dark Absol
    Mar 26 at 22:45











  • I'd say replace doesn't do what you think it does. It doesn't take an index, it takes a string value (or single character), and replace its first occurrence.

    – Bergi
    Mar 26 at 22:46












  • I assume this is what you were alluding to when you mentioned that you know this is not the right way of doing it, but just on the off-chance that it wasn't: python has an easy way to do this: docs.python.org/3/library/stdtypes.html#str.title

    – Kevin Wang
    Mar 26 at 22:50













3












3








3


1






First of all I know that it is not the right way of doing it, but I want to understand why it is happening so I'll better understand the language.



function titleCase(str) 
let str1 = str.toLowerCase();
str1 = str1.replace(str1[0], str1[0].toUpperCase());
console.log(str1);

for(let i=1; i < str1.length; i++)
if(str1[i]===' ')
str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());
console.log(i);
console.log(str1);


return str1;


titleCase("ab cd ef gh ba");


So, if the first letter of the last word doesn't appear as second to last letter in any word before it is working, "ab cd ef gh" no problem here, but "ab cd ef gh ba" results in the following output: "AB Cd Ef Gh ba" etc..
Thanks!










share|improve this question
















First of all I know that it is not the right way of doing it, but I want to understand why it is happening so I'll better understand the language.



function titleCase(str) 
let str1 = str.toLowerCase();
str1 = str1.replace(str1[0], str1[0].toUpperCase());
console.log(str1);

for(let i=1; i < str1.length; i++)
if(str1[i]===' ')
str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());
console.log(i);
console.log(str1);


return str1;


titleCase("ab cd ef gh ba");


So, if the first letter of the last word doesn't appear as second to last letter in any word before it is working, "ab cd ef gh" no problem here, but "ab cd ef gh ba" results in the following output: "AB Cd Ef Gh ba" etc..
Thanks!







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 22:51







leon_h

















asked Mar 26 at 22:39









leon_hleon_h

184 bronze badges




184 bronze badges















  • The logic of your function is not correct. You need to reconsider it.

    – AhmadWabbi
    Mar 26 at 22:44











  • For the record, this function would be much better as: titleCase = str => str.replace(/b[a-z]/, x=>x.toUpperCase());

    – Niet the Dark Absol
    Mar 26 at 22:45











  • I'd say replace doesn't do what you think it does. It doesn't take an index, it takes a string value (or single character), and replace its first occurrence.

    – Bergi
    Mar 26 at 22:46












  • I assume this is what you were alluding to when you mentioned that you know this is not the right way of doing it, but just on the off-chance that it wasn't: python has an easy way to do this: docs.python.org/3/library/stdtypes.html#str.title

    – Kevin Wang
    Mar 26 at 22:50

















  • The logic of your function is not correct. You need to reconsider it.

    – AhmadWabbi
    Mar 26 at 22:44











  • For the record, this function would be much better as: titleCase = str => str.replace(/b[a-z]/, x=>x.toUpperCase());

    – Niet the Dark Absol
    Mar 26 at 22:45











  • I'd say replace doesn't do what you think it does. It doesn't take an index, it takes a string value (or single character), and replace its first occurrence.

    – Bergi
    Mar 26 at 22:46












  • I assume this is what you were alluding to when you mentioned that you know this is not the right way of doing it, but just on the off-chance that it wasn't: python has an easy way to do this: docs.python.org/3/library/stdtypes.html#str.title

    – Kevin Wang
    Mar 26 at 22:50
















The logic of your function is not correct. You need to reconsider it.

– AhmadWabbi
Mar 26 at 22:44





The logic of your function is not correct. You need to reconsider it.

– AhmadWabbi
Mar 26 at 22:44













For the record, this function would be much better as: titleCase = str => str.replace(/b[a-z]/, x=>x.toUpperCase());

– Niet the Dark Absol
Mar 26 at 22:45





For the record, this function would be much better as: titleCase = str => str.replace(/b[a-z]/, x=>x.toUpperCase());

– Niet the Dark Absol
Mar 26 at 22:45













I'd say replace doesn't do what you think it does. It doesn't take an index, it takes a string value (or single character), and replace its first occurrence.

– Bergi
Mar 26 at 22:46






I'd say replace doesn't do what you think it does. It doesn't take an index, it takes a string value (or single character), and replace its first occurrence.

– Bergi
Mar 26 at 22:46














I assume this is what you were alluding to when you mentioned that you know this is not the right way of doing it, but just on the off-chance that it wasn't: python has an easy way to do this: docs.python.org/3/library/stdtypes.html#str.title

– Kevin Wang
Mar 26 at 22:50





I assume this is what you were alluding to when you mentioned that you know this is not the right way of doing it, but just on the off-chance that it wasn't: python has an easy way to do this: docs.python.org/3/library/stdtypes.html#str.title

– Kevin Wang
Mar 26 at 22:50












3 Answers
3






active

oldest

votes


















1














The reason this happens is that the .replace() function will replace the first occurrence.



"Tell us more about your question us"


The first time it finds a space, it will replace the first occurrence of a lowercase "u" which happens to be the correct one:



"Tell us more about your question us"
// ^ this "u" happens to be the first occurrence


But when it comes to the last word "us", it will again try to find the first occurrence of the lowercase "u", which is the one in the middle of the word "about":



"Tell Us More About Your Question us"
// ^ this "u" is now the first lowercase "u"





share|improve this answer
































    1














    for sring replacements of that kind id rather use regex



    using /b(.)/g as pattern for the first letter and U$0 as the substitution string it should work as intended



    here is a fiddle for that



    https://regex101.com/r/qQ2dE4/423






    share|improve this answer
































      0














      This is replacing the first occurrence of the character within the string. So characters at earlier positions are potentially replaced as well.



      str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());





      share|improve this answer



























        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%2f55367187%2fcapitalizing-first-letter-of-every-word-doesnt-work-as-expected%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        The reason this happens is that the .replace() function will replace the first occurrence.



        "Tell us more about your question us"


        The first time it finds a space, it will replace the first occurrence of a lowercase "u" which happens to be the correct one:



        "Tell us more about your question us"
        // ^ this "u" happens to be the first occurrence


        But when it comes to the last word "us", it will again try to find the first occurrence of the lowercase "u", which is the one in the middle of the word "about":



        "Tell Us More About Your Question us"
        // ^ this "u" is now the first lowercase "u"





        share|improve this answer





























          1














          The reason this happens is that the .replace() function will replace the first occurrence.



          "Tell us more about your question us"


          The first time it finds a space, it will replace the first occurrence of a lowercase "u" which happens to be the correct one:



          "Tell us more about your question us"
          // ^ this "u" happens to be the first occurrence


          But when it comes to the last word "us", it will again try to find the first occurrence of the lowercase "u", which is the one in the middle of the word "about":



          "Tell Us More About Your Question us"
          // ^ this "u" is now the first lowercase "u"





          share|improve this answer



























            1












            1








            1







            The reason this happens is that the .replace() function will replace the first occurrence.



            "Tell us more about your question us"


            The first time it finds a space, it will replace the first occurrence of a lowercase "u" which happens to be the correct one:



            "Tell us more about your question us"
            // ^ this "u" happens to be the first occurrence


            But when it comes to the last word "us", it will again try to find the first occurrence of the lowercase "u", which is the one in the middle of the word "about":



            "Tell Us More About Your Question us"
            // ^ this "u" is now the first lowercase "u"





            share|improve this answer













            The reason this happens is that the .replace() function will replace the first occurrence.



            "Tell us more about your question us"


            The first time it finds a space, it will replace the first occurrence of a lowercase "u" which happens to be the correct one:



            "Tell us more about your question us"
            // ^ this "u" happens to be the first occurrence


            But when it comes to the last word "us", it will again try to find the first occurrence of the lowercase "u", which is the one in the middle of the word "about":



            "Tell Us More About Your Question us"
            // ^ this "u" is now the first lowercase "u"






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 26 at 22:46









            rickdenhaanrickdenhaan

            6,48214 silver badges24 bronze badges




            6,48214 silver badges24 bronze badges


























                1














                for sring replacements of that kind id rather use regex



                using /b(.)/g as pattern for the first letter and U$0 as the substitution string it should work as intended



                here is a fiddle for that



                https://regex101.com/r/qQ2dE4/423






                share|improve this answer





























                  1














                  for sring replacements of that kind id rather use regex



                  using /b(.)/g as pattern for the first letter and U$0 as the substitution string it should work as intended



                  here is a fiddle for that



                  https://regex101.com/r/qQ2dE4/423






                  share|improve this answer



























                    1












                    1








                    1







                    for sring replacements of that kind id rather use regex



                    using /b(.)/g as pattern for the first letter and U$0 as the substitution string it should work as intended



                    here is a fiddle for that



                    https://regex101.com/r/qQ2dE4/423






                    share|improve this answer













                    for sring replacements of that kind id rather use regex



                    using /b(.)/g as pattern for the first letter and U$0 as the substitution string it should work as intended



                    here is a fiddle for that



                    https://regex101.com/r/qQ2dE4/423







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 26 at 23:01









                    BaconBacon

                    2042 silver badges5 bronze badges




                    2042 silver badges5 bronze badges
























                        0














                        This is replacing the first occurrence of the character within the string. So characters at earlier positions are potentially replaced as well.



                        str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());





                        share|improve this answer





























                          0














                          This is replacing the first occurrence of the character within the string. So characters at earlier positions are potentially replaced as well.



                          str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());





                          share|improve this answer



























                            0












                            0








                            0







                            This is replacing the first occurrence of the character within the string. So characters at earlier positions are potentially replaced as well.



                            str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());





                            share|improve this answer













                            This is replacing the first occurrence of the character within the string. So characters at earlier positions are potentially replaced as well.



                            str1 = str1.replace(str1[i+1], str1[i+1].toUpperCase());






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 26 at 22:44









                            jspcaljspcal

                            42.6k4 gold badges56 silver badges65 bronze badges




                            42.6k4 gold badges56 silver badges65 bronze badges






























                                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%2f55367187%2fcapitalizing-first-letter-of-every-word-doesnt-work-as-expected%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

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript