0

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.

3
  • 4
    I don't think you are going to solve this with a regex. Commented Feb 6, 2013 at 18:38
  • Why are you trying to avoid to store the script language in the DB? This seems to be the best solution. Commented Feb 6, 2013 at 18:55
  • I'm not trying to avoid storing it in a db. I'm trying to avoid having to mark that as JS in the db. I'm exploring the feasibility of detecting whether or not value coming in is JS. Commented Feb 6, 2013 at 18:58

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget the original javascript parser written in javascript - jslint. The linting is just an application of the underlying code. Hidden in jslint is a very fast, very small js parser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.