shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 508 forks source link

【Q684】实现一个函数 camelCase,对变量转化为驼峰命名 #703

Open shfshanyue opened 3 years ago

jyehn commented 2 years ago
//驼峰转短横线
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'));
rujptw commented 1 year ago
// 字符串转驼峰
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));
Hazel-Lin commented 1 year ago
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'));
justorez commented 9 months ago
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'