This works:
var r="xS";
var regex = new RegExp(r); // Anchor at the end
var s="axS";
s = s.replace( regex, "Z" );
// Now, s is "aZ"
But this doesn't
var r="x$";
var regex = new RegExp(r); // Anchor at the end
var s="ax$";
s = s.replace( regex, "Z" );
// Now, s is STILL "ax$". NOT "aZ".
This doesn't work no matter where "$" is in the string r - e.g even if it's not at the end.