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

后端 未结 5 1798
一个人的身影
一个人的身影 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-08 00:02

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

提交回复
热议问题