How to convert “camelCase” to “Camel Case”?

后端 未结 11 824
北荒
北荒 2020-11-27 10:25

I’ve been trying to get a JavaScript regex command to turn something like \"thisString\" into \"This String\" but the closest I’ve gotten is replac

相关标签:
11条回答
  • 2020-11-27 10:58

    Lodash handles this nicely with _.startCase()

    0 讨论(0)
  • 2020-11-27 11:00

    Not regex, but useful to know plain and old techniques like this:

    var origString = "thisString";
    var newString = origString.charAt(0).toUpperCase() + origString.substring(1);
    
    0 讨论(0)
  • 2020-11-27 11:01

    I had an idle interest in this, particularly in handling sequences of capitals, such as in xmlHTTPRequest. The listed functions would produce "Xml H T T P Request" or "Xml HTTPRequest", mine produces "Xml HTTP Request".

    function unCamelCase (str){
        return str
            // insert a space between lower & upper
            .replace(/([a-z])([A-Z])/g, '$1 $2')
            // space before last upper in a sequence followed by lower
            .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
            // uppercase the first character
            .replace(/^./, function(str){ return str.toUpperCase(); })
    }
    

    There's also a String.prototype version in a gist.

    0 讨论(0)
  • 2020-11-27 11:01

    My version

    function camelToSpace (txt) {
      return txt
        .replace(/([^A-Z]*)([A-Z]*)([A-Z])([^A-Z]*)/g, '$1 $2 $3$4')
        .replace(/ +/g, ' ')
    }
    camelToSpace("camelToSpaceWithTLAStuff") //=> "camel To Space With TLA Stuff"
    
    0 讨论(0)
  • 2020-11-27 11:02

    A solution that handles numbers as well:

    function capSplit(str){
       return str.replace
          ( /(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g
          , function(match, first){
              if (first) match = match[0].toUpperCase() + match.substr(1);
              return match + ' ';
              }
           )
       }
    

    Tested here [JSFiddle, no library. Not tried IE]; should be pretty stable.

    0 讨论(0)
  • 2020-11-27 11:02

    Try this solution here -

    var value = "myCamelCaseText";
    var newStr = '';
    for (var i = 0; i < value.length; i++) {
      if (value.charAt(i) === value.charAt(i).toUpperCase()) {
        newStr = newStr + ' ' + value.charAt(i)
      } else {
        (i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
      }
    }
    return newStr;
    
    0 讨论(0)
提交回复
热议问题