-1

This code, to my thinking, should return aha aha aha, but it returns Aha Aha Aha

"Aha Aha Aha".replace(/([A-Z])/g,"$1".toLowerCase());

Same with toUpperCase()...

"Aha Aha Aha".replace(/([a-z])/g,"$1".toUpperCase());

Any explanation why this is happening?

Daniel
  • 34,125
  • 17
  • 102
  • 150

1 Answers1

3

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    I was just reading thoroughly through this answer http://stackoverflow.com/questions/6142922/replace-a-regex-capture-group-with-uppercase-in-javascript which explains – Daniel Nov 25 '15 at 06:24