javascript - Convert string to camel case

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized.

Examples:

// returns "theStealthWarrior"
console.log(toCamelCase("the-stealth-warrior"));

// returns "TheStealthWarrior"
console.log(toCamelCase("The_Stealth_Warrior"))

去掉中间间隔符,并且从第二个单词开始首字母大写

  • my answer:
function toCamelCase(str) {
  if (str == ''){
    return '';
  }
  var strnew = str.replace(/[^a-zA-Z]/g,'-');
  var a = strnew.split('-');
  for (var i = 1; i < a.length; i++) {    //如果从第一个单词开始首字母大写就改成 i=0;
    a[i] = a[i][0].toUpperCase()+a[i].slice(1);  //首字母大写
  }
  return a.join('');
}
  • best answer:
function toCamelCase(str){
      var regExp=/[-_]\w/ig;
      return str.replace(regExp,function(match){
            return match.charAt(1).toUpperCase();
       });
}
posted @ 2017-09-09 15:35  芒果夏夏  阅读(288)  评论(0编辑  收藏  举报