算法:短线连接格式(learn to code at freeCodeCamp)

题目

算法中级:短线连接格式

在这道题目中,我们需要写一个函数,把一个字符串转换为“短线连接格式”。短线连接格式的意思是,所有字母都是小写,且用-连接。比如,对于Hello World,应该转换为hello-world;对于I love_Javascript-VeryMuch,应该转换为i-love-javascript-very-much。

spinalCase(“This Is Spinal Tap”)应该返回"this-is-spinal-tap"。
spinalCase(“thisIsSpinalTap”)应该返回"this-is-spinal-tap"。
spinalCase(“The_Andy_Griffith_Show”)应该返回"the-andy-griffith-show"。
spinalCase(“Teletubbies say Eh-oh”)应该返回"teletubbies-say-eh-oh"。
spinalCase(“AllThe-small Things”)应该返回"all-the-small-things"。

解题

function spinalCase(str) {
let CharReg = /\s|-|_/g;
//字符串的所有空格 - _字符 替换为-
let clearCharStr = str.replace(CharReg,'-');
let spaceStr = '',
    reg = /[A-Z]/;
 for(let i = 0,len =str.length;i < len;i++){
     let current = clearCharStr[i],
        next =clearCharStr[i-1];
        if(next){
             // 如果当前字符为写大小字母, 且它的上一个字符不为特殊字符-, 则将当前字符加上-字符
            if(reg.test(current) && !(/-/g.test(next)) ){
              clearCharStr  = clearCharStr.replace(current,`-${current}`)
            }
        }
    
 }   
 let newStr = clearCharStr.toLocaleLowerCase(),
    arrStr = newStr.split(/-/);
  return arrStr.join('-')  
  // return str;
}

spinalCase('This Is Spinal Tap');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值