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
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'));