What characters are valid for JavaScript variable names?

后端 未结 12 1882
情深已故
情深已故 2020-11-21 04:26

Which characters can be used for naming a JavaScript variable?

I want to create a small \"extension library\" for my non-JavaScript users here at work (who all seem

12条回答
  •  梦毁少年i
    2020-11-21 04:50

    I've taken Anas Nakawa's idea and improved it. First of all, there is no reason to actually run the function being declared. We want to know whether it parses correctly, not whether the code works. Second, a literal object is a better context for our purpose than var XXX as it's harder to break out of.

        function isValidVarName( name ) {
        try {
            return name.indexOf('}') === -1 && eval('(function() { a = {' + name + ':1}; a.' + name + '; var ' + name + '; }); true');
        } catch( e ) {
            return false;
        }
        return true;
    }
    
    // so we can see the test code
    var _eval = eval;
    window.eval = function(s) {
        console.log(s);
        return _eval(s);
    }
    
    console.log(isValidVarName('name'));
    console.log(isValidVarName('$name'));
    console.log(isValidVarName('not a name'));
    console.log(isValidVarName('a:2,b'));
    console.log(isValidVarName('"a string"'));
    
    console.log(isValidVarName('xss = alert("I\'m in your vars executin mah scrip\'s");;;;;'));
    console.log(isValidVarName('_;;;'));
    console.log(isValidVarName('_=location="#!?"'));
    
    console.log(isValidVarName('ᾩ'));
    console.log(isValidVarName('ĦĔĽĻŎ'));
    console.log(isValidVarName('〱〱〱〱'));
    console.log(isValidVarName('जावास्क्रिप्ट'));
    console.log(isValidVarName('KingGeorgeⅦ'));
    console.log(isValidVarName('}; }); alert("I\'m in your vars executin\' mah scripts"); true; // yeah, super valid'));
    console.log(isValidVarName('if'));
    

提交回复
热议问题