What characters are valid for JavaScript variable names?

后端 未结 12 1884
情深已故
情深已故 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条回答
  •  无人及你
    2020-11-21 05:10

    in case regular expressions is not a must, wouldn't it be better to just ask the browser to decide using eval ?

    function isValidVarName( name ) {
        try {
            // Update, previoulsy it was
            // eval('(function() { var ' + name + '; })()');
            Function('var ' + name);
        } catch( e ) {
            return false;
        }
        return true;
    }
    
    isValidVarName('my_var');     // true
    isValidVarName('1');          // false
    

提交回复
热议问题