Regex /s not working as expected

function spinalCase(str) {
  var reg = new RegExp('\s','g');
  str = str.split('');
  for(i=0;i<str.length;i++){
    str[i] = str[i].toLowerCase();
  }
  str = str.join('');
  str = str.replace(reg,"-");
  return str;
}

I use the regular expression provided in the material recommended by the challenge, but for some reason it targets the character “s” instead of the whitespace. Where my mistake?

In this:

  var reg = new RegExp('\s','g');

the string '\s' is a javascript string so backslashes must be escaped. Instead of \s, you need \\s. If you were making your own regex, then /\s/g would be sufficient.

1 Like

Also, this

can surely just be:

str = str.toLowerCase()

unless I’m missing something? If you’re literally just lowercasing a string, you don’t need to split and join it, the only time you’d need to do that is if you were reversing it.

Thanks! I ended up using [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff] to move forward anyways so…