keyword - Determine if a word is a reserved Javascript identifier - Stack Overflow

Is it possible in Javascript to determine if a certain string is a reserved language keyword such as sw

Is it possible in Javascript to determine if a certain string is a reserved language keyword such as switch, if, function, etc.? What I would like to do is escaping reserved identifiers in dynamically generated code in a way that doesn't break on browser-specific extensions. The only thought ing to my mind is using eval in a try-catch block and check for a syntax error. Not sure how to do that though. Any ideas?

Is it possible in Javascript to determine if a certain string is a reserved language keyword such as switch, if, function, etc.? What I would like to do is escaping reserved identifiers in dynamically generated code in a way that doesn't break on browser-specific extensions. The only thought ing to my mind is using eval in a try-catch block and check for a syntax error. Not sure how to do that though. Any ideas?

Share Improve this question edited Apr 23, 2013 at 4:46 GOTO 0 asked Apr 22, 2013 at 22:10 GOTO 0GOTO 0 48.1k25 gold badges139 silver badges164 bronze badges 2
  • 5 I'd just go here, grab all the reserved words put them in an array and check the string. – elclanrs Commented Apr 22, 2013 at 22:12
  • What's the context of this question? Are you dynamically creating variable names, or just want to make sure when coding that you don't accidentally use a reserved word (in which case, using an IDE or something like Notepad++ will do). Or use jsLint to check for this stff. – David Gilbertson Commented Apr 23, 2013 at 1:02
Add a ment  | 

3 Answers 3

Reset to default 6

One option would be to do:

var reservedWord = false;
try {
  eval('var ' + wordToCheck + ' = 1');
} catch {
  reservedWord = true;
}

The only issue will be that this will give false positive for words that are invalid variable names but not reserved words.

As pointed out in the ments, this could be a security risk.

I guess you could solve it using eval, but that seems like sort of a hack. I would go for just checking against all reserved words. Something like this:

var reservedWords = [
    'break',
    'case',
    ...
];

function isReservedWord(str) {
    return !!~reservedWords.indexOf(str);
}

Here is a list of all reserved words: https://developer.mozilla/en-US/docs/JavaScript/Reference/Reserved_Words

Also, a problem with the eval-approach is that some browsers sometimes allows you to use some reserved words as identifiers.

FYI, Some words throws error only in strict mode

ex: package

eval('var package = 1') // No error
'use strict'
eval('var package = 1') // throws error

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745040256a4607767.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信