0

Input string is "thisIsSpinalTap". I replaced each uppercase letter with it's lowercase version. I also wanted to add a - before the letter to get the spinal case effect "this-is-spinal-tap".

I wrote the following line of code:

str = str.replace(/([A-Z])/g, '-').toLowerCase();

This replaced each uppercase letter with - to produce "this-s-pinal-ap". This was not the desired effect.

I read that using $1 could produce the effect I wanted, and it did.

str = str.replace(/([A-Z])/g, '-$1').toLowerCase();

How does the $1 work to append - to the string, rather than replace the uppercase letter?

1

1 Answer 1

3

$1 is the first group captured in the regular expression.

So in this case, -$1 will replace what was matched with -, followed by the uppercase letter captured in ([A-Z]).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.