我一直在尝试获取一个 JavaScript 正则表达式命令来将类似的东西"thisString"变成"This String",但我得到的最接近的方法是替换一个字母,导致类似"Thi String"or的东西"This tring"。有任何想法吗?
"thisString"
"This String"
"Thi String"
"This tring"
澄清一下,我可以处理大写字母的简单性,我只是没有 RegEx 强大,拆分"somethingLikeThis"是"something Like This"我遇到麻烦的地方。
"somethingLikeThis"
"something Like This"
"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>