0

The aim of the challenge is to create a hyphened word chaining. My question is how I could create an all-encompassing regex for the scenarios shown below:

I am able to do the first, third and fourth example.

function spinalCase(str) {

  let result =str.toLowerCase().split(/\W/) 
  result.join('-')
  return result;
}

spinalCase('This Is Spinal Tap');
spinalCase("Teletubbies say Eh-oh"); 
spinalCase("The_Andy_Griffith_Show"); 
spinalCase("thisIsSpinalTap")// My code does not work on these
spinalCase("AllThe-small Things")// My code does not work on these

1 Answers1

1

You can use the following regular expression:

Reference: https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-123.php

var spinalCase = function(str) {

  var converted = str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.toLowerCase())
    .join('-');
  console.log(converted)
  return converted;
};



spinalCase('This Is Spinal Tap');
spinalCase("Teletubbies say Eh-oh");
spinalCase("The_Andy_Griffith_Show");
spinalCase("thisIsSpinalTap")
spinalCase("AllThe-small Things")
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35