前端百题斩【022】——开拓思路之三种方式实现字符串转驼峰
2023-09-27 14:25:56 时间
相信大家都遇到过这样一个问题 将 - 连接的字符串转换为驼峰形式 例如将hello-word转换为helloWorld。这个问题虽然简单 但是如果仅仅用一种方案进行解决不能体现 出自己的能力 如果要想表现的与众不同 就要用多种方式解决。下面就通过三种方式解决该问题。
首先来看看第一种方案 是在字符串维度进行操作 其思想可以归结为以下几个步骤
// 操作字符串数组 function transformStr2CamelCase1(str) { if (typeof(str) ! string ) { return const strArr str.split( - for (let i i strArr.length; i ) { strArr[i] strArr[i].charAt(0).toUpperCase() strArr[i].substring(1); return strArr.join( console.log(transformStr2CamelCase1( hello-world // helloWorld
第二种方案是在字符维度进行动刀 因为小写变大写的字符都是在 - 后面的字符 所以在遇到 - 后将其变为大写 其步骤如下
// 操作字符数组 function transformStr2CamelCase2(str) { if (typeof(str) ! string ) { return const strArr str.split( for (let i i strArr.length; i ) { if (strArr[i] - ) { // 删除- strArr.splice(i, 1); // 将此处改为大写 if (i strArr.length) { strArr[i] strArr[i].toUpperCase(); return strArr.join( console.log(transformStr2CamelCase2( hello-world // helloWorld
方式三则是利用正则的方式去匹配字符串中的内容 然后将匹配到的内容替换掉 其步骤如下
确定对应的正则表达式 利用replace方法 将对应的小写字符转换为大写。// 利用正则 function transformStr2CamelCase3(str) { if (typeof(str) ! string ) { return const reg /-(\w)/g; return str.replace(reg, function ($0, $1) { return $1.toUpperCase(); console.log(transformStr2CamelCase3( hello-world // helloWorld