Spinal Tap solved, but I still don't understand regexp

My code that solves the challenge below:

function spinalCase(str) {
 	var regExp = /[^-_\s][a-z]*/g; // exclude '-','_',whitespace
  var result = [];
  var words = str.match(regExp);
  var wordCount = words.length;
  
  for (var i = 0; i < wordCount; i++) {
    if ( i < wordCount - 1) {
      result.push ( words[i] + '-');
    }
    else {
      result.push( words[i] );
    }
  }
  return result.join("").toLowerCase();
}

I used the online regex tools from here, but the part I do not understand is how is [a-z] including whole words that begin with an uppercase letter? To me, my regex pattern shouldn’t even be working yet it apparently satisfies the challenge.

The first part matches anything that is not a dash, underscore, or whitespace. Uppercase characters would be selected by that.

2 Likes

I think I understand what you mean, and [a-z]* that follows I am saying the 2nd letter in the matching expression must be zero or more occurrences of a lowercase letter? I think is what I am doing here.

Yup, that’s it. :+1: