题目描述

假设一个字符串存在以 - . _ 三种单词分隔符形式,请实现一个字符串转换函数,将该字符串的单词分隔符去掉,转换为驼峰形式

camelizeStr("hello_world") // helloWorld
camelizeStr("hello-world") // helloWorld
camelizeStr("hello.world") // helloWorld
camelizeStr("how_old-are.you") // howOldAreYou
camelizeStr("how__old--are..you") // howOldAreYou
camelizeStr("_test") // Test
camelizeStr(".") // ''

思路&js代码

1、正则替换

function camelizeStr(str) {
  const res = str.replace(/[\-\.\_]{1,}[a-z]*/g, s => {
    const s2 = s.replace(/[\-\.\_]/g, "")
    if (s2.length === 0) return ""
    return s2[0].toUpperCase() + s2.slice(1)
  })
  console.log(res)
  return res
}

2、进阶-转换object

伪代码

function camelizeObj(obj, depth) {
  let arr = [obj]
  let _depth = depth // 2
 
  while (depth) {
    const newArr = arr.map(obj => {
      const tmp = Object.keys(obj).map(key => {
        const newKey = camelizeStr(key)
        obj[newKey] = obj[key]
        delete obj[key]
        if (typeof obj[newKey] === "object ") return obj[newKey]
      })
      return tmp
    })
    arr = flat(newArr)
    _depth--
  }
 
  return obj
}