js 驼峰命名转烤串

直接贴代码吧:

/**
 * 驼峰命名转烤串
 * @param camelStr - 驼峰字符串
 * @return {string} - 烤串类型的字符串
 * example ModifyJDRelatedOrderID -> modify-jd-related-order-id
 */
function camelToKebab (camelStr = '') {
  // 判断是否是 大驼峰
  const isUpper = camelStr[0].charCodeAt() >= 65 && camelStr[0].charCodeAt() <= 90
  const handleStr = camelStr.replace(/([A-Z])/g, '-$1').toLowerCase()
  let kebabStr = handleStr
  if (isUpper) {
    kebabStr = handleStr.slice(1)
  }
  // 处理连续大写的情况
  const newKebabArr = []
  const kebabSplitArr = kebabStr.split('-')
  kebabSplitArr.forEach((item, index) => {
    if (item.length > 1) {
      newKebabArr.push(item)
    } else {
      let combineStr = ''
      const subKebabArr = kebabSplitArr.slice(index)
      for (let i = 0; i < subKebabArr.length; i++) {
        if (subKebabArr[i].length > 1) break
        combineStr += subKebabArr[i]
      }
      newKebabArr.push(combineStr)
      kebabSplitArr.splice(index + 1, combineStr.length - 1)
    }
  })
  return newKebabArr.join('-')
}

参考:

js驼峰和中划线连字符相互转化的最佳实践

程序变量命名的几种叫法

posted @ 2021-04-19 09:42  暗恋桃埖源  阅读(260)  评论(0编辑  收藏  举报