將字符串轉換爲以-連接的全小寫單詞

將字符串轉換爲 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)function spinalCase(str) {
  return str.replace(/_/g,'').replace(/([A-Z])/g," $1").replace(/^\s/,"").replace(/\s+/g,'-').toLowerCase();
}

spinalCase('The_Andy_Griffit');

2)function spinalCase(str) {
   function replacer(match){
     return ' ' + match;
   }
   if (str[0] <= 'z'&& str[0] >= 'a'){
     str =str.replace(/[A-Z]+/g,replacer);
   }
   str = str.replace(/\s/g,'-').replace(/_/g,'-').toLowerCase();
   return str;
 }
 spinalCase('This Is Spinal Tap');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章