我一直试图得到一个JavaScript regex命令,把类似“thisString”的东西变成“This String”,但我得到的最接近的是替换一个字母,导致类似“This String”或“This String”的东西。什么好主意吗?

为了澄清我可以处理大写字母的简单性,我只是不太擅长RegEx,把“somethingLikeThis”分割成“somethingLikeThis”是我遇到麻烦的地方。


当前回答

Lodash用_.startCase()很好地处理了这个问题

其他回答

"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>

const value = 'camelCase';
const map = {};
let index = 0;
map[index] = [];
for (let i = 0; i < value.length; i++) {
  if (i !== 0 && value[i] === value[i].toUpperCase()) {
    index = i;
    map[index] = [];
  }
  if (i === 0) {
    map[index].push(value[i].toUpperCase());
  } else {
    map[index].push(value[i]);
  }
}
let resultArray = [];
Object.keys(map).map(function (key, index) {
  resultArray = [...resultArray, ' ', ...map[key]];
  return resultArray;
});
console.log(resultArray.join(''));

不是正则表达式,但知道这些简单而古老的技巧是有用的:

var origString = "thisString";
var newString = origString.charAt(0).toUpperCase() + origString.substring(1);

我的版本

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"

Lodash用_.startCase()很好地处理了这个问题