我发现 this example 将 CamelCase 更改为 Dashes。
我已修改代码以将 CamelCase 更改为 Sentencecase,其中包含空格而不是破折号。它工作正常,但不适用于一个单词的字母,例如“i”和“a”。任何想法如何合并?
var str = "thisIsAPain";
str = camelCaseToSpacedSentenceCase(str);
alert(str)
function camelCaseToSpacedSentenceCase(str)
{
var spacedCamel = str.replace(/\W+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2");
spacedCamel = spacedCamel.toLowerCase();
spacedCamel = spacedCamel.substring(0,1).toUpperCase() + spacedCamel.substring(1,spacedCamel.length)
return spacedCamel;
}
最佳答案
最后一个版本:
"thisIsNotAPain"
.replace(/^[a-z]|[A-Z]/g, function(v, i) {
return i === 0 ? v.toUpperCase() : " " + v.toLowerCase();
}); // "This is not a pain"
旧的解决方案:
"thisIsAPain"
.match(/^(?:[^A-Z]+)|[A-Z](?:[^A-Z]*)+/g)
.join(" ")
.toLowerCase()
.replace(/^[a-z]/, function(v) {
return v.toUpperCase();
}); // "This is a pain"
console.log(
"thisIsNotAPain"
.replace(/^[a-z]|[A-Z]/g, function(v, i) {
return i === 0 ? v.toUpperCase() : " " + v.toLowerCase();
}) // "This is not a pain"
);
console.log(
"thisIsAPain"
.match(/^(?:[^A-Z]+)|[A-Z](?:[^A-Z]*)+/g)
.join(" ")
.toLowerCase()
.replace(/^[a-z]/, function(v) {
return v.toUpperCase();
}) // "This is a pain"
);
关于JavaScript:正则表达式 CamelCase 到 Sentence,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13720256/