Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Last active January 11, 2020 19:45
Show Gist options
  • Select an option

  • Save martin-mok/5494d6499ac7c5d3331baed5c31586aa to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/5494d6499ac7c5d3331baed5c31586aa to your computer and use it in GitHub Desktop.
freecodecamp: Spinal Tap Case

Description

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

Tests

tests:
  - text: <code>spinalCase("This Is Spinal Tap")</code> should return <code>"this-is-spinal-tap"</code>.
    testString: assert.deepEqual(spinalCase("This Is Spinal Tap"), "this-is-spinal-tap");
  - text: <code>spinalCase("thisIsSpinal<wbr>Tap")</code> should return <code>"this-is-spinal-tap"</code>.
    testString: assert.strictEqual(spinalCase('thisIsSpinalTap'), "this-is-spinal-tap");
  - text: <code>spinalCase("The_Andy_<wbr>Griffith_Show")</code> should return <code>"the-andy-griffith-show"</code>.
    testString: assert.strictEqual(spinalCase("The_Andy_Griffith_Show"), "the-andy-griffith-show");
  - text: <code>spinalCase("Teletubbies say Eh-oh")</code> should return <code>"teletubbies-say-eh-oh"</code>.
    testString: assert.strictEqual(spinalCase("Teletubbies say Eh-oh"), "teletubbies-say-eh-oh");
  - text: <code>spinalCase("AllThe-small Things")</code> should return <code>"all-the-small-things"</code>.
    testString: assert.strictEqual(spinalCase("AllThe-small Things"), "all-the-small-things");

Solution

Offical soln:

function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  str = str.replace(/([a-z](?=[A-Z]))/g, '$1 ');
  return str.toLowerCase().replace(/\ |\_/g, '-');
}

Other solns:
Spinal Tap Case - Hugh Winchester
identifying where there is difference in case, and inserting a dash in between those two characters.

function spinalCase(str) {
 return str.replace(/([a-z])([A-Z])/g, ‘$1-$2’)
 .replace(/\s+|_+/g, -)
 .toLowerCase();
//returns   'this-is-spinal-tap'
}
spinalCase(‘This Is_Spinal Tap’);

Bonfire Spinal Tap Case

function spinalCase(str) {
  // Create a variable for the white space and underscores.
  var regex = /\s+|_+/g;

  // Replace low-upper case to low-space-uppercase
  str = str.replace(/([a-z])([A-Z])/g, '$1 $2');

  // Replace space and underscore with -
  return str.replace(regex, '-').toLowerCase();
}

repl.it/@iyeradith/Spinal-Tap-Case

function spinalCase(str) 
{
  return str.split(/\s+|_+|(?=[A-Z])/).join("-").toLowerCase();
}

spinalCase('This Is Spinal___Tap');

Useful Links

Regular Expressions: Use Capture Groups to Search and Replace

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment