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

后端 未结 11 941
北荒
北荒 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 11:06

    "thisStringIsGood"
        // insert a space before all caps
        .replace(/([A-Z])/g, ' $1')
        // uppercase the first character
        .replace(/^./, function(str){ return str.toUpperCase(); })
    

    displays

    This String Is Good
    

    (function() {
    
      const textbox = document.querySelector('#textbox')
      const result = document.querySelector('#result')
      function split() {
          result.innerText = textbox.value
            // insert a space before all caps
            .replace(/([A-Z])/g, ' $1')
            // uppercase the first character
            .replace(/^./, (str) => str.toUpperCase())
        };
    
      textbox.addEventListener('input', split);
      split();
    }());
    #result {
      margin-top: 1em;
      padding: .5em;
      background: #eee;
      white-space: pre;
    }
    Text to split

提交回复
热议问题