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):
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();