-1

The idea of this function is to turn camelCase into spinal-case by using regex capture groups to capture the capital letters, make the modifications and then reinsert them. The capture group works but the replacement function does not and I'm beginning to get regex migraines.

function spinalCase(str) {
  var regexp = /([A-Z]{1})/g;
  var match;
  var matches = "";
  var myRegexp;
  while ((match = regexp.exec(str)) != null) {
    matches = "-" + match[1].toLowerCase();
    //matches = "t", "i", "s", "t"
    myRegexp = new RegExp(match[1], "g");
    str.replace(myRegexp, matches);
  }
  return str;
  //returns the original string without modifications
}
console.log(spinalCase('ThisIsSpinalTap'));
j08691
  • 204,283
  • 31
  • 260
  • 272
Henry S
  • 35
  • 1
  • 6

1 Answers1

1

This entire function can be replaced by a simple one-liner in ES6:

var spinalCase = str => str.replace(/[A-Z]/g, match => '-' + match.toLowerCase());

Pre ES6 (but not quite equivalent due to hoisting rules):

function spinalCase(str) {
    return str.replace(/[A-Z]/g, function(match) {
        return '-' + match.toLowerCase();
    }
}
wizzwizz4
  • 6,140
  • 2
  • 26
  • 62