Open shfshanyue opened 3 years 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));
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'));
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'