Vincent Tang
Vincent Tang

Reputation: 4170

Regex to target adjacent lowercase and uppercase Char

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

Answers (2)

Rory
Rory

Reputation: 3410

You need brackets around the parts you expect to be $1 and $2.

/([a-z]+)([A-Z])/

Upvotes: 1

Dust_In_The_Wind
Dust_In_The_Wind

Reputation: 3692

Using capturing groups -

function tap(str) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2');
}

console.log(tap('ThisIsSpinalTap'));

Upvotes: 4

Related Questions