小编典典

如何将“camelCase”转换为“Camel Case”?

all

我一直在尝试获取一个 JavaScript 正则表达式命令来将类似的东西"thisString"变成"This String",但我得到的最接近的方法是替换一个字母,导致类似"Thi String"or的东西"This tring"。有任何想法吗?

澄清一下,我可以处理大写字母的简单性,我只是没有 RegEx 强大,拆分"somethingLikeThis""something Like This"我遇到麻烦的地方。


阅读 117

收藏
2022-07-04

共1个答案

小编典典

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

显示

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>
2022-07-04