Search code examples
regexcoldfusionrailocfml

Capitalize first letter of first word in a every sentence in ColdFusion


I want to get a string like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tempor pulvinar enim! Nec aliquam massa faucibus sed?? Praesent nec consectetur sapien... Nulla dapibus rutrum turpis, ac porta erat posuere vel.

starting from string in all uppercase (or lowercase). For example:

LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT. DONEC TEMPOR PULVINAR ENIM! NEC ALIQUAM MASSA FAUCIBUS SED?? PRAESENT NEC CONSECTETUR SAPIEN... NULLA DAPIBUS RUTRUM TURPIS, AC PORTA ERAT POSUERE VEL.

How can I do? Thank you!


Solution

  • Take your text and set it to a variable like this:

    <cfset stringFixer = "LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT. DONEC TEMPOR PULVINAR ENIM! NEC ALIQUAM MASSA FAUCIBUS SED?? PRAESENT NEC CONSECTETUR SAPIEN... NULLA DAPIBUS RUTRUM TURPIS, AC PORTA ERAT POSUERE VEL.">
    

    Lowercase everything:

    <cfset stringFixer = lCase(stringFixer)>
    

    Then you will need to match your string terminator with rematch like this:

    <cfset stringFixerBreaker = reMatch('\w.+?[.?]+',stringFixer)>
    

    reMatch() will break apart your string into smaller discrete sentence strings...Then you could do a replaceNoCase() with left search for the first char then do the same with your replacement string which will be the same but we will throw a uCase() on that first character to capitalize it.

    <cfloop array="#stringFixerBreaker#" index="i">
    <cfoutput>#replaceNoCase(i,left(i, 1 ),uCase(left(i, 1 )))# </cfoutput>
    </cfloop>  
    

    Your output will look like this:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tempor pulvinar enim! nec aliquam massa faucibus sed?? Praesent nec consectetur sapien... Nulla dapibus rutrum turpis, ac porta erat posuere vel.
    

    Edit: One last touch point to my answer.

    If you need to rebuild the string do this:

    <cfset str = "">
    
    <cfloop array="#stringFixerBreaker#" index="i">
        <cfset str = str & replaceNoCase(i,left(i, 1 ),uCase(left(i, 1 ))) & " ">
    </cfloop>  
    

    Dump out the results to check everything is in order:

    <cfdump var="#str#">