Search code examples
javascriptregexgoogle-chromereplacecapturing-group

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.


Solution

  • (/-(\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"