function convertToCamelCase (str) { var returnStr; if (str.charAt(0) === '-') { returnStr = str.substring(1).split('-') } else { returnStr = str.split('-') } console.log(returnStr) for (var i = 1; i<returnStr.length; i++) { returnStr[i] = returnStr[i][0].toUpperCase() + returnStr[i].substring(1) } return returnStr.join('') } console.log(convertToCamelCase('background-img-img2'))
方法二:
function convertToCamelCase (str) { var returnStr = str.split('-'); if (returnStr[0] === '') { returnStr.shift() } for (var i = 1; i<returnStr.length; i++) { if (returnStr[i] !== '') { returnStr[i] = returnStr[i][0].toUpperCase() + returnStr[i].substring(1) } } return returnStr.join('') } console.log(convertToCamelCase('-background-img-cas'))