Spinal Tap Case

What is "Spinal case" ?

  所謂的spinal case就是用小寫跟dash(-)連結所有的單字,Ex: all-lowercase-words-joined-by-dashes這樣的形式

  function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  var regex = /[A-Z]/g;
  return (str[0] == str[0].toUpperCase()) ? str.replace(/[\s]/g, '-').replace(/_/g, '-').toLowerCase():
                                            str.replace(regex,'-' + '$&').toLowerCase();
}
spinalCase('This Is Spinal Tap');
spinalCase("thisIsSpinalTap");
spinalCase("The_Andy_Griffith_Show");
spinalCase("Teletubbies say Eh-oh");

Solution:

觀察可以發現大寫開頭的字串,單詞之間都有空格或者底線連結,所以將這些符號換成dash(-)即可,然後如果是以小寫開頭的字串,則須在大寫字園前插入dash(-),然後將所有的字元轉成小寫,置換字元時,則是使用Regulae Expression將檢測到的字串,轉換為欲轉換的字元



P.S. / Reference:  String.prototype.replace()
          RegExp

results matching ""

    No results matching ""