I have come across a piece of code in JScript:
RegExp.$1
Does anybody know what it does?
If I output it on its own, I get nothing not even an error.
I can't find any reference to it at http://www.w3schools.com/jsref/jsref_obj_regexp.asp
There was a regex search just prior to this piece of code, which I suspect has something to do with it:
.search(/^__product\[(.+)\]$/)
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.
$1 equals the text " brown ".
$1 refers to the first match, $2 to the second one. The expected contents of the num string is thus 11222,333 after this bit of code. Show activity on this post. This is how jQuery users a variable called $ as an alias for the jQuery object.
Regular expressions are particularly useful for defining filters. Regular expressions contain a series of characters that define a pattern of text to be matched—to make a filter more specialized, or general. For example, the regular expression ^AL[.]* searches for all items beginning with AL.
The literal expression RegExp.$1
will get you the value of the first capture group of the last regex ran. Whatever that regex was.
For example:
var match = /_(.*)_/.exec('_test_');
var newMatch = '123-abc'.match(/(\d*)-(\w*)/);
var num = RegExp.$1; // '123';
RegExp.$1
is globally available, so it can be accessed from anywhere in your page, regardless of where the regex itself was ran.
I've never seen this syntax used before seeing this question, and I wouldn't suggest using it, as I cannot find documentation on it. Also, any regex ran on your page, regardless of where, will modify this property. If you want to get the capture groups, I'd use the arrays returned from String.match
or RegExp.exec
instead.
EDIT: I found some documentation about this: http://msdn.microsoft.com/en-us/library/ie/24th3sah(v=vs.94).aspx
EDIT 2: I found some more info about this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#RegExp_Properties
RegExp.$1
is deprecated. That means future browsers might remove this "feature", so I suggest not using it.
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