Spinal Tap Case WARNING! ANSWER!

Spinal Tap Case WARNING! ANSWER!
0.0 0

#1

Tell us what’s happening:
what is a shorter way to do this (better RegEx ?)
i feel like i used way too many variables when i could have somehow used 2

Your code so far

function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  // create regex to check spaces or underlines against.
  var a = /\s_/g;
  //insert spaces before capital letters that are at word boundries, meaning not adding extra spaces before a word that already has one, or replacing letters with spaces. and then trim off spaces from before or after string
 var b = str.replace(/\B([A-Z])/g, " $1").trim();
  /*the '$1' , in a replace method , refers to the REPLACEMENT PATERN. as the MDN documentation says
  $n	Where n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. Note that this is 1-indexed.
  */
  //turn string into lower case letters
  var c = b.replace(/_/g,"").toLowerCase();
 // call return statement that replaces regex in variable 'a' with dashes
return c.replace(/\s/g,'-');
}

spinalCase('The_Andy_Griffith_Show');

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36.

Link to the challenge:


#2

#3

#4

I edited your code by a putting [spoiler] before your code and a [/spoiler] after your code, so as not to spoil the solution for someone else.

To answer you question, get rid of the variable a assignment, because you are not using it anywhere else in your solution. Also, you do not need trim() and you can chain the replace functions like:

function spinalCase(str) {
  return str.replace(/\B([A-Z])/g, " $1")
    .replace(/_/g,"").toLowerCase()
    .replace(/\s/g,'-');
}

#5

isn’t chaining replace functions resource consuming?


#6

I would not think any more than your separate replace functions called individually.


#7

true, i was asking more if it could be shortened to two functions