Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Cannot Delete RegExp.$1 in JavaScript

Cannot Delete RegExp.$1 in JavaScript

Problem

Anyone know why are the Regexp.$1-x variables are not settable to undefined?

Following example in nodejs. Same behavior in chrome/firefox:

console.log('1:', RegExp.$1, RegExp.$2, RegExp.$3, RegExp.$4); 
// 1: / Users/tiefenma/Desktop/ test.js .js

var string = 'test1 test2 test3';
var test = string.match(/(test1).*(test2).*(test3)/gm);


console.log('2:', RegExp.$1, RegExp.$2, RegExp.$3, RegExp.$4);
// 2: test1, test2, test3


RegExp.$1 = undefined;
RegExp.$2 = undefined;
RegExp.$3 = undefined;
console.log('3:', RegExp.$1, RegExp.$2, RegExp.$3, RegExp.$4);
// 3: test1, test2, test3


delete RegExp.$1;
delete RegExp.$2;
delete RegExp.$3;
console.log('4:', RegExp.$1, RegExp.$2, RegExp.$3, RegExp.$4);
// 4: test1, test2, test3


''.match(/(.*)/g);
console.log('5:', RegExp.$1, RegExp.$2, RegExp.$3, RegExp.$4);
// 5:
Problem courtesy of: tiefenb

Solution

Object.getOwnPropertyDescriptor(RegExp, "$1") will give you information about $1:

Chrome 30:

{ 
    get: function, 
    set: function, 
    enumerable: true, 
    configurable: false
}

Firefox 22:

{
    configurable: false,
    enumerable: true, 
    value: "", 
    writable: false
}

Note that configurable is false; so, you can't delete the property. Also, when writable is false, you can't assign a value.

configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.

writable
True if and only if the value associated with the property may be changed with an assignment operator. Defaults to false.

So, in Chrome and Firefox, the implementation prevents you from deleting $1 or assigning a value to $1 with =.

As a point of comparison, IE10 reports things a little differently...

Internet Explorer 10:

{
    value: "",
    writable: true,
    enumerable: false,
    configurable: true
}

That said, IE10 still won't let you delete the property or assign a value to it. Go figure.

Solution courtesy of: canon

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Cannot Delete RegExp.$1 in JavaScript

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×