我有这种类型的单词:
study_one
orange_two
color_blue...etc.
我想将这些单词转换为:
Study One
Orange Two
Color Blue
或
StudyOne
OrangeTwo
ColorBlue
我一直在尝试:
"study_one".replace(/([A-Z])/g, '_$1').substring(1);
答案 0 :(得分:2)
用下划线替换空格并将单词的第一个字母转换为大写:
function toCsCase(str) {
return str.replace(/_/, " ").replace(/(\b[a-z])/g, function(a, b) {
return a.toUpperCase()
});
}
console.log(toCsCase("study_one"));
答案 1 :(得分:1)
复制并粘贴此文件,它应该可以正常工作!
function toCsCase(str){
var x = str.split("_");
var uc = [];
for(var i = 0;i < x.length;i++)
{
uc.push(ucword(x));
}
return uc.join(" ");
}
function ucword(word)
{
return word.charAt(0).toUpperCase() + word.substr(1);
}
答案 2 :(得分:1)
var string = 'study_one';
console.log('Result:', doMagic(string));
function doMagic(str) {
return str
// capitalize the first letter and all characters after underscore
.replace(/^(.)|_(.)/g, function($1) { return $1.toUpperCase(); })
// remove all underscores
.replace(/_/g, '');
}