Problem with regular expression and string.replace - freeCodeCamp Spinal Tap Case

Hi guys, I have a problem with my Spinal Tap Case code. I have a regular expression to separate input strings by space and Upper Character. This is my regular expression:

re = /([a-z]|[A-Z0-9])[a-z-]*/g;

When I test this RE on RegexR I see that the string “thisIsSpinalTap” is breaked based in UpperCase characters (see printscreen below):

But when I use this RE code on replace function it don´t matches in pieces which I expected. The match is on big string.

My code:

function spinalCase(str) {

  function hyphenWords(match, p1, offset, string){
    return match+'-';
  re = /([a-z]|[A-Z0-9])[a-z-]*/g;
  var newStr = str.toLowerCase().replace(re, hyphenWords);
  return newStr.substring(0, newStr.length-1).replace(/\s|_/g,'');
//spinalCase('This Is Spinal Tap');
VM1259:5 thisisspinaltap

I need some help to fix that.


Twitter: @frbcindev

I’ve discovered the error: at line where I’ve declared var newStr, the toLowerCase() call is wrong. I’ve removed it and everything works as expected.

1 Like

Thanks for sharing your solution!

1 Like

Hello guys, I got the solution.

In my above code I tried to split the string and join, but even with a fewer lines of code we can get the solution.

All we need to do is replace unwanted part of string with what we need.

spinalCase(“thisIsSpinalTap”) – In this case we can use $operator in regular expression. Two ranges of characters, a-z and A-Z. Characters from these ranges are grouped together. So we need to identify the two characters which are from taken from two respective ranges(For example: “sI”, “sS” and “lT”) .
Then we need to separate these two characters with a space " ". Which we can do by using $operator

str.replace(/([a-z])([A-Z])/g, '$1 $2');

And in the next step, we need to identify the characters which are not alphabets and digits, which we can obtain by using regular expression /W, but it includes _ underscore. So to eliminate underscore we should except it from the regexp. Which we can by using | or Operator.
Then we need to replace these characters with - hyphen.

str.replace(/\W|_/g, "-");

Finally we convert the string to lower case using .toLowerCase() method.

My Solution is:

function spinalCase(str) {
var newArr= str.replace(/([a-z])([A-Z])/g, ‘$1 $2’).replace(/\W|_/g, “-”);
str = newArr.toLowerCase();
return str;
spinalCase(‘This Is Spinal Tap’);

I also got another way of solving this problem, with your very same regEx.

const regEx = /([a-z]|[A-Z0-9])[a-z-]*/g;

// Now you simply return the strings that match your regEx
// joined with the "-", and in lower case.
// That is

return str.match(regEx).join("-").toLowerCase();

Hope it makes some sense too.