How to explain “$1,$2” in Javascript when using regular expression?

后端 未结 5 1803
一个人的身影
一个人的身影 2020-12-07 23:11

A piece of Javascript code is as follows:

    num=\"11222333\";
    re = /(\\d+)(\\d{3})/;
    re.test(num);
    num.replace(re, \"$1,$2\");
<
5条回答
  •  再見小時候
    2020-12-07 23:42

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

提交回复
热议问题