Spinal Tap Case

Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.

spinalCase("This Is Spinal Tap") should return the string this-is-spinal-tap.

spinalCase("thisIsSpinalTap") should return the string this-is-spinal-tap.

spinalCase("The_Andy_Griffith_Show") should return the string the-andy-griffith-show.

spinalCase("Teletubbies say Eh-oh") should return the string teletubbies-say-eh-oh.

spinalCase("AllThe-small Things") should return the string all-the-small-things.

如何识别大写字母???

Code Explanation

  • Split the string at one of the following conditions (converted to an array)
    • a whitespace character [\s] is encountered
    • underscore character [_] is encountered
    • or is followed by an uppercase letter [(?=[A-Z])]
  • Join the array using a hyphen (-)
  • Lowercase the whole resulting string

Lookaheads: match a string depending on what follows it

Use ?= to match a string that’s followed by a specific substring:

/Roger(?=Waters)/

/Roger(?= Waters)/.test(‘Roger is my dog’) //false

/Roger(?= Waters)/.test(‘Roger is my dog and Roger Waters is a famous musician’)

//true

?! performs the inverse operation, matching if a string is not followed by a specific substring:

/Roger(?!Waters)/

/Roger(?! Waters)/.test(‘Roger is my dog’) //true

/Roger(?! Waters)/.test(‘Roger is my dog and Roger Waters is a famous musician’)

//false

  1. function spinalCase(str) {
  2. str = str.split(/\s|_|(?=[A-Z])/).join("-").toLowerCase();
  3. return str;
  4. }
  5. console.log(
  6. spinalCase('thisIsSpinalTap')
  7. )

https://forum.freecodecamp.org/t/a-quick-and-simple-guide-to-javascript-regular-expressions/190263

https://forum.freecodecamp.org/t/javascript-string-prototype-replace-replace-explained-with-examples/15942