如何解释"$ 1,$ 2"在JavaScript中使用正则表达式时? [英] How to explain "$1,$2" in JavaScript when using regular expression?
问题描述
一段JavaScript代码如下:
A piece of JavaScript code is as follows:
num = "11222333";
re = /(\d+)(\d{3})/;
re.test(num);
num.replace(re, "$1,$2");
我无法理解"$ 1,$ 2"
的语法.带有此代码的书说 $ 1
表示 RegExp.$ 1
, $ 2
表示 RegExp.$ 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:
-
众所周知,在JavaScript中,变量名称应以字母或_开头,在这里
$ 1
如何成为RegExp成员变量的有效名称?
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?
如果我输入 $ 1
,则命令行显示未定义.如果我输入"$ 1"
,则命令行仅回显 $ 1
,而不是11222.因此,replace方法如何知道 $ 1,$ 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?
谢谢.
推荐答案
它不是变量",-在 .replace()
调用中使用的占位符. $ n
表示正则表达式的 nth
个捕获组.
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,$ 2"在JavaScript中使用正则表达式时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!