I\'m reading Sitepoints 2007 book \"Simply Javascript\" and I encountered some code I just can\'t understand.
It\'s the following code:
Core.removeCl
$1 is a backreference. It will be replaced by whatever the first matching group (set of parenthesis) in your regex matches.
Each pair of parentheses (
...)
where the first character is not a ?
* is a "capturing group", which places its result into $1
,$2
,$3
,etc which can be used in the replacement pattern.
You might also see the same thing as \1
,\2
,\3
in other regex engines, (or indeed in the original expression sometimes, for repetition)
These are called "backreferences", because they generally refer back to (an earlier) part of in the expression.
(*The ?
indicates various forms of special behaviour, including a non-capturing group which is (?:
...)
and simply groups without capturing.)
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. (The closing expression ( |$)
is the inverse - a space or the string end position - and since its value isn't used, could have been non-capturing with (?: |$)
instead.)
Hopefully this explains everything ok - let me know if you want any more info.
Also, here's some further reading from the site regular-expressions.info: