Time and time again I see $1 and $2 being used in code. What does it mean? Can you please include examples?
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
A piece of JavaScript code is as follows: num = "11222333"; re = /(\d+)(\d{3})/; re. test(num); num. replace(re, "$1,$2");
$ means "Match the end of the string" (the position after the last character in the string).
In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.
When you create a regular expression you have the option of capturing portions of the match and saving them as placeholders. They are numbered starting at $1
.
For instance:
/A(\d+)B(\d+)C/
This will capture from A90B3C
the values 90
and 3
. If you need to group things but don't want to capture them, use the (?:...)
version instead of (...)
.
The numbers start from left to right in the order the brackets are open. That means:
/A((\d+)B)(\d+)C/
Matching against the same string will capture 90B
, 90
and 3
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With