A piece of JavaScript code is as follows:
num = "11222333";
re = /(\d+)(\d{3})/;
re.test(num);
num.replace(re, "$1,$2");
I could not understand the grammar of "$1,$2". The book from which this code comes says $1 means RegExp.$1, $2 means RegExp.$2. But these explanations lead to more questions:
It is known that in JavaScript, the name of variables should begin with letter or _, how can
$1be a valid name of member variable of RegExp here?If I input
$1, the command line says it is not defined; if I input"$1", the command line only echoes$1, not 11222. So, how does the replace method know what"$1,$2"mean?
Thank you.
$1is a$nreplacement pattern). Also see string literals - JavaScript has no "interpolation" as found in PHP or Perl.$name = "Fred"; print "Hello $name!"might result in "Hello Fred!". One text-book definition of interpolation is to "Insert (something) between fixed points" and in computer languages this often means "Insert value of a variable/expression into a string". JavaScript does not have this feature. Because this is not present in JavaScript it can be concluded that"$1,$2"results in a string of 5 characters and does not interpolate values from any variables - the special handling is then from theString.replacefunction (which I also linked).