I was playing with .replace() recently and found the following behaviour odd. Take the two following code snippets:
const str = "Hello world";
const res = str.replace(/(o)/g, "$1".repeat(3));
console.log(res); // Hellooo wooorld (which I expected)
The above print "Hellooo wooorld", which I expected, as I am using .repeat(3) on the matched o characters.
However, when I apply the same logic and use .toUpperCase(), my string remains unchanged:
const str = "Hello world";
const res = str.replace(/(o)/g, "$1".toUpperCase());
console.log(res); // Hello world (expected HellO wOrld)
The above, to my surprise, didn't work as it printed the original string and not "HellO wOrld". So, why does the first code snippet work but the second doesn't?. I am aware that I can use the replacement function for this, but I am more concerned about understanding why the first snippet works, and the second doesn't.