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

后端 未结 5 1815
一个人的身影
一个人的身影 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条回答
  •  旧时难觅i
    2020-12-07 23:45

    The book from which this code comes says $1 means RegExp.$1, $2 means RegExp.$2.

    This book is made of paper. And paper cannot oppose any resistance to whom is writing on it :-) . But perhaps did you only misinterpret what is actually written in this book.

    Actually, it is depending on the context.

    1. In the context of the replace() method of String, $1, $2, ... $99 (1 through 99) are placeholders. They are handled internally by the replace() method (and they have nothing to do with RegExp.$1, RegExp.$2, etc, which are probably not even defined (see point 2. )). See String.prototype.replace() #Specifying_a_string_as_a_parameter. Compare this with the return value of the match() method of String when the flag g is not used, which is similar to the return value of the exec() method of RegExp. Compare also with the arguments passed implicitly to an (optional) function specified as second argument of replace().
    2. RegExp.$1, RegExp.$2, ... RegExp.$9 (1 through 9 only) are non-standard properties of RegExp as you may see at RegExp.$1-$9 and Deprecated and obsolete features. They seem to be implemented on your browser, but, for somebody else, they could be not defined. To use them, you need always to prepend $1, $2, etc with RegExp.. These properties are static, read-only and stored in the RegExp global object, not in an individual regular expression object. But, anyway, you should not use them. The $1 through $99 used internally by the replace() method of String are stored elsewhere.

    Have a nice day!

提交回复
热议问题