Reputation: 4170
function spinalCase(str) {
//Replace aB to a-B
return str.replace(/[a-z]+[A-Z]/,'$1,-,$2');
}
spinalCase('ThisIsSpinalTap');
I want this input "ThisIsSpinalTap" to output "This-Is-Spinal-Tap" by using a regex to target lowercase letters adjacent to uppercase, and adding a -
inbetween. Incorrect output I am getting is this.
t$1,$2sspinaltap
MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Upvotes: 2
Views: 231
Reputation: 3410
You need brackets around the parts you expect to be $1 and $2.
/([a-z]+)([A-Z])/
Upvotes: 1
Reputation: 3692
Using capturing groups -
function tap(str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2');
}
console.log(tap('ThisIsSpinalTap'));
Upvotes: 4