首页 > 其他 > 详细

Spinal Tap Case(freecodemap)

时间:2017-08-24 17:38:20      阅读:299      评论:0      收藏:0      [点我收藏+]

将字符串转换为 spinal case。Spinal case 是 all-lowercase-words-joined-by-dashes 这种形式的,也就是以连字符连接所有小写单词。

示例:

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"。

 

 1 <html>
 2     <head>
 3         <title></title>
 4         <script type="text/javascript">
 5             window.onload = function(){
 6                 function spinalCase(str) {
 7                 
 8                     //str = str.replace(/\s|_/g,"-");
 9                     function upperToHyphenLower(match,p1,p2,offset){
10                         //match:所匹配的子串(如:_A)
11                         //p1,p2:第n个括号匹配的串(如:_)
12                         //offset:匹配到的子串在原串中的偏移量(如:匹配到This中的T,此时offset=0)
13                         match = match.replace(p1,"");
14                         match = match.replace(p2,"");//将空格、下划线移除
15                         if(offset === 0){
16                             return match.toLowerCase();
17                         }else{
18                             return "-"+match.toLowerCase();
19                         }
20                         
21                     }
22                     //([ _]?)[A-Z]
23                     //后边在加上([ _]),是为了匹配到Teletubbies say
24                     return str.replace(/([ _]?)[A-Z]|([ _])/g,upperToHyphenLower);
25                 }
26 
27                 spinalCase(This Is spinal tap);
28                 spinalCase(The_Andy_Griffith_Show);
29                 spinalCase(Teletubbies say Eh-oh);
30             }
31         </script>
32     </head>
33     <body>
34     
35     </body>
36 </html>

 

replace方法

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace

 

Spinal Tap Case(freecodemap)

原文:http://www.cnblogs.com/suifengershi/p/7423970.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!