Understand $0 and $1 in Javascript Regular Expression

An prototype to extend exec method

Including parentheses in a regular expression pattern causes the corresponding submatches to be remembered. For example, /a(b)c/ matches the characters 'abc' and remembers 'b', in which ‘abc’ may be stored in $0, and ‘b’ may be stored in group $1. /a(b)c(d)e/ matches the character ‘abcde’ and remembers ‘b’ in $1 and remembers ‘d’ in $2. The number of groups could be the number of parentheses used in regular expression. But in most cases, we only deal with one group. So for the 1st step, understand the trick is very useful.

There may be more than one submatch for $1. But our current methods only remember 1 submatch and they perform differently. Exec - RegExp method remembers the 1st submatch while match – string method remembers the last submatch.

For example, /\=(\w+)/g submatches the values of the url

    var str ='http://www.pagecolumn.com/tool/regtest.htm?par1=value1&par2=value2&par3=value3';
exec method
    var re = new RegExp("\=(\w+)", "g");
    var myArray = re.exec(str); 
return: value1 in $1
match method
    var myArray = str.match(/\=(\w+)/g);
return: value3 in $1

We need a way to retrieve all submatches. Here is an example to use replace method. Actually, the captured groups are remember in this example.

    var str = "border-top-width";
    str = str.replace(/-(\w)/gi, function($0,$1) {
        return $0.replace($0,$1.toUpperCase());		
return: "borderTopWidth"

The elegant way is all captured groups are pushed into an array. Here we extended the String object to retrieve all $1 elements.

      String.prototype.$1elements=function(vregex) {
        var elm=[];
        var str=this;
        var re= new RegExp(vregex, "g");
        str = str.replace(re, function($0,$1) {
            return $0;		
        return elm;
        var strs = "border-top-width".$1elements("-(\\w)");
return: t,w

It should be noted here regular expression is used as a parameter of function. The type of augment of is string. There must be an escape character before the special characters of input string.

I would do another experiment. I remove parentheses in the regular expression. The regexp becomes /-\w+/ and it is put it in the above function (don't forget the escape character \).

    var str = "border-top-width".$1elements("-\\w");
return: 6,10

An interesting result. $1 remembers the index of matched string if without parentheses.

Social Bookmark if the page is useful.