用正则表达式下划线将小写单词study_one转换为StudyOne javascript

时间:2018-06-27 15:55:19

标签: javascript

我有这种类型的单词:

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);

3 个答案:

答案 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, '');
}