Reputation: 7576
I'm trying to find out if it's possible to detect if a given string is JavaScript script for the purpose of automatically setting Ace editor more.
'Rules of engagement' would be such that I can have the following:
var x = function(){
alert('hello world');
}
... can this be 'validated' safely as JS? Unfortunately, this would be stored in a DB so I can't rely on a file type extension. In a worst case I might have to mark it as JS content, but for now I'm trying to avoid that.
Upvotes: 0
Views: 122
Reputation: 50807
It's a heavy-weight solution, but you can certainly run a full Javascript parser on it. There are a number of them written in Javascript, such as Uglify, Narcissus, Esprima, Acorn, and ZeParser.
Presumably any of those would tell you if your string contained legitimate Javascript, as well as giving you a full syntax tree of it in the case that it does.
I'm not sure of any more lightweight technique, though.
Upvotes: 3