Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

regex - How to explain "$1,$2" in JavaScript when using regular expression?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...