It doesn't work because you are applying .toUpperCase
to the string "$1"
, which is of course left unchanged. The unchanged string is then passed to the .replace
function, and the result is... well, nothing happens.
The correct way of doing this would be to use a callback:
str.replace(/[a-z]/g,function(m) {return m.toUpperCase();});
(I'm assuming of course that this is an exercise - in this particular case, str.toUpperCase()
directly would be much better!)
Passing a callback to .replace()
is a very powerful thing. The important thing to be aware of is that the arguments passed to it will be the whole match first, then the first subpattern and so on. That is why I have removed the ()
in your regex - they are unnecessary.