I came across this example in MDN documentation on using the replace method on strings.
This is the example cited there
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
print(newstr);//Smith,John
I changed the regex to the following and tested it.
var re = /(\w?)(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$1, $1");
newstr;//J, ohn Smith
var newstr1=str.replace(re,"$2, $1");
newstr1;//ohn, J Smith.
$1 must be J and $2 must be ohn Smith in this example.
when I reversed the order of $n for newstr1,it should be 'ohn Smith, J`. but it is not.
is my understanding of $1 and $2 (substring matches correct) and why newstr1 is different?
Thanks for the comments