Spinal Tap Case - Only Regex Solution

Spinal Tap Case - Only Regex Solution
0

Tell us what’s happening:

So I couldn’t complete the challenge as I tried an all regex approach and took a hint.
Could anyone suggest an all regex approach using only split and not replace

Regex i had done :

[_\s]*(?=[A-Z])

But it doesnt match spaces only, without any uppercase character .Any advice?
Your code so far


function spinalCase(str) {
  // "It's such a fine line between stupid, and clever."
  // --David St. Hubbins
  return str.replace(/([a-z])([A-Z])/g, '$1 $2').split(/[\s_]+/g).join("-").toLowerCase();
}

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/76.0.3809.100 Safari/537.36.

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

Edit: Sorry I forgot you need to account for capital letters, I have amended it for you.

Try this as your regex:

  const regex = /[\W]|[\s]|[_]||(?=[A-Z])/g;

What I have done is said check for anything which is:

NOT a word [\W],
OR |,
IS a space [\s],
OR |,
IS an underscore [_],
OR |,
IS a word with a capital (?=[A-Z])

RegexPal is a great place to test your regexes. Take a note that I have used a lookahead for the final check, this says match expressions which are followed by a specified sequence, in our case, capital letter.

I’m sorry but your regex didn’t work , maybe it was miswritten :slight_smile:

Anway , I reached the following regex:

[\s_]|\s-_)

But it does work in AllThe-small Things case i,e. when uppercase letter is without any space

What is the rest of your code? It is passing all tests for me with the following:

function spinalCase(str) {
  const regex = /[\W]|[\s]|[_]|(?=[A-Z])/g;
  let newStr = str.split(regex);
  return newStr.join('-').toLowerCase();
}
1 Like

sorry i only tried your codeon regexpal website .
Appreciate your help.
Thank man

No problem, happy to help!

1 Like