mrplow
mrplow

Reputation: 163

Is it possible to verify that a given text is JavaScript code?

Upvotes: 0

Views: 102

Answers (1)

Aurelien Ribon
Aurelien Ribon

Reputation: 7634

Of course! Just use a JS parser, such as Esprima (a reference in the industry), and do:

function isIsReallyJSCodeOrWhat(code) {
  try {
    esprima.parse(code);
  } catch (err) {
    return false;
  }

  return true;
}

It's that simple. JS parsers (esprima, acorn, etc.) are all based on the Estree specification. Try having a look at the AST produced by esprima.parse. It's simple to read, and to modify. This way, you can check that the code does nothing you don't want, that it does not refer to some specific variables, etc.

If you want to quickly test some code and see what AST it produces, go to http://esprima.org/demo/parse.html.

Upvotes: 2

Related Questions