Spinal Tap Case- RegExp

Spinal Tap Case- RegExp
0

#1

Tell us what’s happening:
Can anyone help me with finding the right regexps for my code?

Your code so far


function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  var splitArr= str.split(/\W+/);
  var lowerCaseArr = splitArr.map(function(val) {
    return val.toLowerCase();
  })
  console.log(lowerCaseArr);
  return lowerCaseArr.join("-");
}

spinalCase('This Is Spinal Tap');

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case/


#2

Hello guys, I got the solution. I want to help others to achieve this.

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 splitArr= str.replace(/([a-z])([A-Z])/g, ‘$1 $2’).replace(/\W|_/g, “-”);
str = splitArr.toLowerCase();
return str;
}
spinalCase(‘This Is Spinal Tap’);


#3

Nice! Here’s what I did. I chose to split the string wherever there’s either a non-alphanumeric character or a capital letter, which we detect via a lookahead to avoid making a match that would omit the letter. Because underscores, to my surprise, count as alphanumeric characters, I had to negate them in regex to treat them as non-alphanumeric.

function spinalCase(str) {
    let words = str.split(/[\W^_]+|(?=[A-Z])/).map(w => w.toLowerCase());
    return words.join('-');
}

#4

Dude this solution is freakin’ HOTTT. Wow :slight_smile: