string/camelCase.jsjavascript
/**
* 拆分大小写和分隔符组成的单词。
* @private
*/
function words(value) {
return value.trim().replace(/([a-z\d])([A-Z])/g, '$1 $2').split(/[\s_-]+/).filter(Boolean)
}
/**
* 将字符串转换为小驼峰命名。
* @function camelCase
* @memberof module:string
* @param {string} value 原字符串
* @returns {string} 小驼峰字符串
* @throws {TypeError} 参数不是字符串时抛出
*/
function camelCase(value) {
if (typeof value !== 'string') throw new TypeError('value must be a string')
return words(value).map((word, index) => {
const normalized = word.toLowerCase()
return index === 0 ? normalized : `${normalized[0].toUpperCase()}${normalized.slice(1)}`
}).join('')
}
export default camelCase