How to convert "camelCase" to "Camel Case"?

Solution 1:

"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;
}
<div>
  Text to split
  <input id="textbox" value="thisStringIsGood" />
</div>

<div id="result"></div>

Solution 2:

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.