Skip to content

Instantly share code, notes, and snippets.

@jcolebot
Created April 15, 2022 14:19
Show Gist options
  • Select an option

  • Save jcolebot/a6846186b9bb630a6d00511119ec339d to your computer and use it in GitHub Desktop.

Select an option

Save jcolebot/a6846186b9bb630a6d00511119ec339d to your computer and use it in GitHub Desktop.
freeCodeCamp: Covert a String to Spinal Case Solution
// Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
// Regex + Join Method
function spinalCase(str) {
return str
.split(/[\s_]+|(?=[A-Z])/g)
.join("-")
.toLowerCase();
}
// Regex + Replace Method
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment