fCC Spinal Tap Case Challenge - How Do You Match Underscore With Regex?

I can match everything but underscores : regex101: build, test, and debug regex

/(?<=[a-z])[A-Z]|\W+/

I’ve spent the last couple hours trying searching for answers and trying several different variations on what this. It matches everything else but I can not get it to include the underscores.

The paste linked above shows explicitly what I have so far.

Any suggestions?




function spinalCase(str) {
return str;
}

spinalCase('This Is Spinal Tap');
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0

Challenge: Spinal Tap Case

Link to the challenge:

I go it. Sorry for the trouble…

/(?<=[a-z])[A-Z]|\W+|[_]/g

Works

Ok, I was wrong and I still need help.

As it turns out…

function spinalCase(str) {
  
  //
  // Replace separators with dashes (ie: dashes, underscores, spaces, upper camel no space)
  // Use regex
  // Convert to lower case last
  //
  
  return str.replace(/(?<=[a-z])[A-Z]|\W+|[_]/g, '-').toLowerCase().trim();
}

console.log(spinalCase('This Is Spinal Tap'));
console.log(spinalCase("thisIsSpinalTap"));
console.log(spinalCase("The_Andy_Griffith_Show"));
console.log(spinalCase("Teletubbies say Eh-oh"));
console.log(spinalCase("AllThe-small Things"));

https://onecompiler.com/javascript/3xuvhg8t9

Using…

/(?<=[a-z])[A-Z]|\W+/g

…actually replaces the capital letters in upper camel case cases with underscore (rather than inserting an underscore before the capital letter / between the words).

Any suggestions on how I can solve this?


I think there is a backspace atom for regex? Is it \b or something? Would that help?

I figured it out… thanks

function spinalCase(str) {
  if(/(?<=[a-z])[A-Z]/.test(str)) str = str.replace(/([A-Z])/g, ' $1').trim();
  return str.replace(/(?<=[a-z])[A-Z]|\W+|[_]/g, '-').toLowerCase().trim();
}

console.log(spinalCase('This Is Spinal Tap'));
console.log(spinalCase("thisIsSpinalTap"));
console.log(spinalCase("The_Andy_Griffith_Show"));
console.log(spinalCase("Teletubbies say Eh-oh"));
console.log(spinalCase("AllThe-small Things"));

https://onecompiler.com/javascript/3xuvhg8t9

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.