高级前端手写代码【Q684】实现一个函数 camelCase,对变量转化为驼峰命名

实现一个函数 camelCase,对变量转化为驼峰命名

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 703

Author 回答者: jyehn

//驼峰转短横线
function toKebabCase(str) {
  let res = str.replace(/([A-Z])/g, (all, i) => {
    return "-" + i.toLowerCase();
  });
  if (res.slice(0, 1) === "-") {
    res = res.slice(1); //去除开头的-
  }
  return res;
}
//短横线转驼峰
function toCamelCase(str) {
  return str.replace(/-([a-zA-Z])/g, function (all, i) {
    return i.toUpperCase();
  });
}
 
console.log(toCamelCase("get-element-by-id"));
console.log(toKebabCase("GetElementById"));

Author 回答者: rujptw

// 字符串转驼峰
let str = "--talk-much--"
let str2 = "__talk_much__"
let str3 = "Talk Much"
let reg = /([-|_|\s]\w)/g;
function camelCase(str){
  let formatStr = str.replace(reg,function(match){
    return match.slice(1).toUpperCase()
  })
  formatStr = formatStr.replace(/[-|_|\s]/g,'')
  formatStr = formatStr[0].toLowerCase() + formatStr.slice(1,formatStr.length+1)
  return formatStr
}
console.log("camelCase",camelCase(str));
console.log("camelCase",camelCase(str2));
console.log("camelCase",camelCase(str3));

Author 回答者: Hazel-Lin

const camelCase = (variableName) => {
  const wordList = variableName.split(/[-_\s]+/);
  let camelCaseList = wordList.map((word, index) => {
    if (!index) {
      return word.toLowerCase();
    }
    return word.charAt(0).toUpperCase() + word.slice(1);
  });
  return camelCaseList.join("");
};
 
console.log(camelCase("third variable"));
console.log(camelCase("Third variable"));
console.log(camelCase("third_variable"));
console.log(camelCase("third-variable"));
console.log(camelCase("thirdVariable"));

Author 回答者: justorez

function camelCase(str) {
  return str
    .split(/[\-_\s]+/)
    .filter((w) => w !== "")
    .reduce((prev, cur, index) => {
      if (index === 1) prev = prev.toLowerCase();
      cur = cur.charAt(0).toUpperCase() + cur.slice(1).toLowerCase();
      return prev + cur;
    });
}
 
camelCase("fooBar");
// => 'fooBar'
 
camelCase("Foo Bar");
// => 'fooBar'
 
camelCase("--foo-bar--");
// => 'fooBar'
 
camelCase("__FOO_BAR__");
// => 'fooBar'