Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with second argument of simple `replace()`

I don't understand, why doesn't this code work properly?

"a-b".replace(/-(\w)/g, p1 => p1.toUpperCase()); // "a-B", instead of "aB"

It has to be simplest solution for exchanging CSS's hyphen-syntax on camelCase.

like image 479
Dima Parzhitsky Avatar asked Feb 10 '26 05:02

Dima Parzhitsky


1 Answers

(/-(\w)/g).exec("a-b")
// [ "-b", "b" ]

So, "b" is the second argument passed to the replace callback, the first argument is the whole match.

"a-b".replace(/-(\w)/g, (p1, p2) => p2.toUpperCase())
// "aB"

EDIT it would be more clear written this way:

"a-b".replace(/-(\w)/g, (match, p1) => p1.toUpperCase())
// "aB"
like image 181
pawel Avatar answered Feb 15 '26 15:02

pawel