Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  133] [ 1]  / answers: 1 / hits: 88618  / 11 Years ago, wed, may 22, 2013, 12:00:00

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:



  1. 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?



  2. 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.


More From » regex

 Answers
17

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));




[#78076] Tuesday, May 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gageherberth

Total Points: 249
Total Questions: 115
Total Answers: 119

Location: Liechtenstein
Member since Sun, Sep 12, 2021
3 Years ago
;