Convert camelCaseText to Sentence Case Text

后端 未结 20 2050
闹比i
闹比i 2020-11-28 03:44

How can I convert a string either like \'helloThere\' or \'HelloThere\' to \'Hello There\' in JavaScript?

相关标签:
20条回答
  • 2020-11-28 04:12

    The best string I've found for testing camel-case-to-title-case functions is this ridiculously nonsensical example, which tests a lot of edge cases. To the best of my knowledge, none of the previously posted functions handle this correctly:

    __ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D

    This should be converted to:

    To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D

    If you want just a simple function that handles cases like the one above (and more cases than many of the previously answers), here's the one I wrote. This code isn't particularly elegant or fast, but it's simple, understandable, and works.

    The snippet below contains an online runnable example:

    var mystrings = [ "__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D", "helloThere", "HelloThere", "ILoveTheUSA", "iLoveTheUSA", "DBHostCountry", "SetSlot123ToInput456", "ILoveTheUSANetworkInTheUSA", "Limit_IOC_Duration", "_This_is_a_Test_of_Network123_in_12__days_",  "ASongAboutTheABCsIsFunToSing", "CFDs", "DBSettings", "IWouldLove1Apple", "Employee22IsCool", "SubIDIn",  "ConfigureABCsImmediately", "UseMainNameOnBehalfOfSubNameInOrders" ];
    
    // Take a single camel case string and convert it to a string of separate words (with spaces) at the camel-case boundaries.
    // 
    // E.g.:
    //    __ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D
    //                                            --> To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D
    //    helloThere                              --> Hello There
    //    HelloThere                              --> Hello There 
    //    ILoveTheUSA                             --> I Love The USA
    //    iLoveTheUSA                             --> I Love The USA
    //    DBHostCountry                           --> DB Host Country
    //    SetSlot123ToInput456                    --> Set Slot 123 To Input 456
    //    ILoveTheUSANetworkInTheUSA              --> I Love The USA Network In The USA
    //    Limit_IOC_Duration                      --> Limit IOC Duration
    //    This_is_a_Test_of_Network123_in_12_days --> This Is A Test Of Network 123 In 12 Days
    //    ASongAboutTheABCsIsFunToSing            --> A Song About The ABCs Is Fun To Sing
    //    CFDs                                    --> CFDs
    //    DBSettings                              --> DB Settings
    //    IWouldLove1Apple                        --> I Would Love 1 Apple
    //    Employee22IsCool                        --> Employee 22 Is Cool
    //    SubIDIn                                 --> Sub ID In
    //    ConfigureCFDsImmediately                --> Configure CFDs Immediately
    //    UseTakerLoginForOnBehalfOfSubIDInOrders --> Use Taker Login For On Behalf Of Sub ID In Orders
    //
    function camelCaseToTitleCase(in_camelCaseString) {
            var result = in_camelCaseString                         // "__ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser_456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
                .replace(/(_)+/g, ' ')                              // " ToGetYourGEDInTimeASongAboutThe26ABCsIsOfTheEssenceButAPersonalIDCardForUser 456InRoom26AContainingABC26TimesIsNotAsEasyAs123ForC3POOrR2D2Or2R2D"
                .replace(/([a-z])([A-Z][a-z])/g, "$1 $2")           // " To Get YourGEDIn TimeASong About The26ABCs IsOf The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times IsNot AsEasy As123ForC3POOrR2D2Or2R2D"
                .replace(/([A-Z][a-z])([A-Z])/g, "$1 $2")           // " To Get YourGEDIn TimeASong About The26ABCs Is Of The Essence ButAPersonalIDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
                .replace(/([a-z])([A-Z]+[a-z])/g, "$1 $2")          // " To Get Your GEDIn Time ASong About The26ABCs Is Of The Essence But APersonal IDCard For User456In Room26AContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
                .replace(/([A-Z]+)([A-Z][a-z][a-z])/g, "$1 $2")     // " To Get Your GEDIn Time A Song About The26ABCs Is Of The Essence But A Personal ID Card For User456In Room26A ContainingABC26Times Is Not As Easy As123ForC3POOr R2D2Or2R2D"
                .replace(/([a-z]+)([A-Z0-9]+)/g, "$1 $2")           // " To Get Your GEDIn Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3POOr R2D2Or 2R2D"
                
                // Note: the next regex includes a special case to exclude plurals of acronyms, e.g. "ABCs"
                .replace(/([A-Z]+)([A-Z][a-rt-z][a-z]*)/g, "$1 $2") // " To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"
                .replace(/([0-9])([A-Z][a-z]+)/g, "$1 $2")          // " To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456In Room 26A Containing ABC 26Times Is Not As Easy As 123For C3PO Or R2D2Or 2R2D"  
    
                // Note: the next two regexes use {2,} instead of + to add space on phrases like Room26A and 26ABCs but not on phrases like R2D2 and C3PO"
                .replace(/([A-Z]{2,})([0-9]{2,})/g, "$1 $2")        // " To Get Your GED In Time A Song About The 26ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
                .replace(/([0-9]{2,})([A-Z]{2,})/g, "$1 $2")        // " To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
                .trim()                                             // "To Get Your GED In Time A Song About The 26 ABCs Is Of The Essence But A Personal ID Card For User 456 In Room 26A Containing ABC 26 Times Is Not As Easy As 123 For C3PO Or R2D2 Or 2R2D"
               ;
    
      // capitalize the first letter
      return result.charAt(0).toUpperCase() + result.slice(1);
    }
    
    for (var i = 0; i < mystrings.length; i++) {
      jQuery(document.body).append("<br />\"");
      jQuery(document.body).append(camelCaseToTitleCase(mystrings[i]));
      jQuery(document.body).append("\"<br>(was: \"");
      jQuery(document.body).append(mystrings[i]);
      jQuery(document.body).append("\") <br />");
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

    0 讨论(0)
  • 2020-11-28 04:13

    Here's my version of it. It adds a space before every UpperCase english letter that comes after a lowercase english letter and also capitalizes the first letter if needed:

    For example:
    thisIsCamelCase --> This Is Camel Case
    this IsCamelCase --> This Is Camel Case
    thisIsCamelCase123 --> This Is Camel Case123

      function camelCaseToTitleCase(camelCase){
        if (camelCase == null || camelCase == "") {
          return camelCase;
        }
    
        camelCase = camelCase.trim();
        var newText = "";
        for (var i = 0; i < camelCase.length; i++) {
          if (/[A-Z]/.test(camelCase[i])
              && i != 0
              && /[a-z]/.test(camelCase[i-1])) {
            newText += " ";
          }
          if (i == 0 && /[a-z]/.test(camelCase[i]))
          {
            newText += camelCase[i].toUpperCase();
          } else {
            newText += camelCase[i];
          }
        }
    
        return newText;
      }
    
    0 讨论(0)
  • 2020-11-28 04:14

    None of the answers above worked perfectly for me, so had to come with own bicycle:

    function camelCaseToTitle(camelCase) {
        if (!camelCase) {
            return '';
        }
    
        var pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.substr(1);
        return pascalCase
            .replace(/([a-z])([A-Z])/g, '$1 $2')
            .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
            .replace(/([a-z])([0-9])/gi, '$1 $2')
            .replace(/([0-9])([a-z])/gi, '$1 $2');
    }
    

    Test cases:

    null => ''
    '' => ''
    'simpleString' => 'Simple String'
    'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside'
    'stringWithNumber123' => 'String With Number 123'
    'complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc'
    
    0 讨论(0)
  • 2020-11-28 04:19

    I didn't try everyone's answer, but the few solutions I tinkered with did not match all of my requirements.

    I was able to come up with something that did...

    export const jsObjToCSSString = (o={}) =>
        Object.keys(o)
              .map(key => ({ key, value: o[key] }))
              .map(({key, value}) =>
                  ({
                    key: key.replace( /([A-Z])/g, "-$1").toLowerCase(),
                    value
                  })
              )
              .reduce(
                  (css, {key, value}) => 
                      `${css} ${key}: ${value}; `.trim(), 
                  '')
    
    0 讨论(0)
  • 2020-11-28 04:23

    I think this can be done just with the reg exp /([a-z]|[A-Z]+)([A-Z])/g and replacement "$1 $2".

    ILoveTheUSADope -> I Love The USA Dope

    0 讨论(0)
  • 2020-11-28 04:24

    One more solution based on RegEx.

    respace(str) {
      const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g;
      return str.replace(regex, '$& ');
    }
    

    Explanation

    The above RegEx consist of two similar parts separated by OR operator. The first half:

    1. ([A-Z]) - matches uppercase letters...
    2. (?=[A-Z][a-z]) - followed by a sequence of uppercase and lowercase letters.

    When applied to sequence FOo, this effectively matches its F letter.

    Or the second scenario:

    1. ([a-z]) - matches lowercase letters...
    2. (?=[A-Z]) - followed by an uppercase letter.

    When applied to sequence barFoo, this effectively matches its r letter.

    When all replace candidates were found, the last thing to do is to replace them with the same letter but with an additional space character. For this we can use '$& ' as a replacement, and it will resolve to a matched substring followed by a space character.

    Example

    const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g
    const testWords = ['ACoolExample', 'fooBar', 'INAndOUT', 'QWERTY', 'fooBBar']
    
    testWords.map(w => w.replace(regex, '$& '))
    ->(5) ["A Cool Example", "foo Bar", "IN And OUT", "QWERTY", "foo B Bar"]
    
    0 讨论(0)
提交回复
热议问题