JS——字符串转驼峰

1. 方法

/** 
 * @param str 字符串
 * @param separator 分割符(默认"-")
 * @param topIsCapital 开头是否大写(默认是)
 */
function toHump(str, separator = "-", topIsCapital = true) {
    
    
  let strAry = str.split(separator)
  return strAry.map((item, index) => {
    
    
    if (!topIsCapital && index == 0) return item
    return item.replace(/^./, item.match(/^./)[0].toLocaleUpperCase())
  }).join("")
}

2. 使用

toHump("hello-word") //HelloWord
toHump("hello_word","_") //HelloWord
toHump("hello_word","_",false) //helloWord

猜你喜欢

转载自blog.csdn.net/qq812457115/article/details/128934898
今日推荐