防止JavaScript中的RegExp构造函数的污染属性

And*_*y E 15 javascript regex

这是一个难题,我知道如何能够解决它,但我想知道是否有一个(更多)更简单的方法.

简而言之,只要在JavaScript中执行正则表达式,就会在RegExp构造函数上为某些属性赋值.例如:

/foo/.test('football')
//-> true

RegExp.input
//-> "football"

RegExp.rightContext
//-> "tball"
Run Code Online (Sandbox Code Playgroud)

我想在不影响这些属性的情况下执行正则表达式.如果那是不可能的(而且我认为不可能),那么我想至少将它们恢复到以前的值.

我知道input/ $_是可写的,但其他大多数都不是,似乎.一种选择可能是重建一个重新应用所有这些值的正则表达式,但我认为这将是非常困难的.

我想要这个的原因是因为我正在编写一个原生API垫片,并使用test262套件进行测试.test262套件在某些测试中失败,它检查RegExp对象是否具有这些属性的意外值.

And*_*y E 1

这是最终结果。它比我最初的努力更稳健一些;它正确地转义子表达式,确保它们以正确的顺序出现,并且在发现空表达式时不会停止:

/**
 * Constructs a regular expression to restore tainted RegExp properties
 */
function createRegExpRestore () {
    var lm  = RegExp.lastMatch,
        ret = {
           input: RegExp.input
        },
        esc = /[.?*+^$[\]\\(){}|-]/g,
        reg = [],
        cap = {};

    // Create a snapshot of all the 'captured' properties
    for (var i = 1; i <= 9; i++)
        cap['$'+i] = RegExp['$'+i];

    // Escape any special characters in the lastMatch string
    lm = lm.replace(esc, '\\$0');

    // Now, iterate over the captured snapshot
    for (var i = 1; i <= 9; i++) {
        var m = cap['$'+i];

        // If it's empty, add an empty capturing group
        if (!m)
            lm = '()' + lm;

        // Else find the escaped string in lm wrap it to capture it
        else
            lm = lm.replace(m.replace(esc, '\\$0'), '($0)');

        // Push to `reg` and chop `lm`
        reg.push(lm.slice(0, lm.indexOf('(') + 1));
        lm = lm.slice(lm.indexOf('(') + 1);
    }

    // Create the property-reconstructing regular expression
    ret.exp = RegExp(reg.join('') + lm, RegExp.multiline ? 'm' : '');

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

它完成了我最初认为困难的事情。如果您像这样使用它,这应该将所有属性恢复到以前的值:

var 
    // Create a 'restore point' for RegExp
    old  = createRegExpRestore(),

    // Run your own regular expression
    test = someOtherRegEx.test(someValue);

// Restore the previous values by running the RegExp
old.exp.test(old.input);
Run Code Online (Sandbox Code Playgroud)