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 $1
be 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.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs. All digits that follow $ are interpreted as belonging to the number group.
$1 is the first group from your regular expression, $2 is the second. Groups are defined by brackets, so your first group ($1) is whatever is matched by (\d+). You'll need to do some reading up on regular expressions to understand what that matches.
$1 is a backreference. It will be replaced by whatever the first matching group (set of parenthesis) in your regex matches. In this case $1 will be nothing (if the first group matches the 0-width ^ start of line character) or a space (if the first group matches a space).
In JavaScript, regular expressions are often used with the two string methods: search() and replace() . The search() method uses an expression to search for a match, and returns the position of the match. The replace() method returns a modified string where the pattern is replaced.
It's not a "variable" - it's a placeholder that is used in the .replace()
call. $n
represents the nth
capture group of the regular expression.
var num = "11222333"; // This regex captures the last 3 digits as capture group #2 // and all preceding digits as capture group #1 var re = /(\d+)(\d{3})/; console.log(re.test(num)); // This replace call replaces the match of the regex (which happens // to match everything) with the first capture group ($1) followed by // a comma, followed by the second capture group ($2) console.log(num.replace(re, "$1,$2"));
$1 is the first group from your regular expression, $2 is the second. Groups are defined by brackets, so your first group ($1) is whatever is matched by (\d+). You'll need to do some reading up on regular expressions to understand what that matches.
It is known that in Javascript, the name of variables should begin with letter or _, how can $1 be a valid name of member variable of RegExp here?
This isn't true. $ is a valid variable name as is $1. You can find this out just by trying it. See jQuery and numerous other frameworks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With