2

How could a Commando like me check if inputed code is a valid JavaScript source using some JavaScript built-in methods (if any!) or in any other possible way!? (Something like a preparser found in various IDE's like NetBeans, Eclipse, etc)?

I have to check if code is OKAY and then window.eval()-it to the current document instance.

pppery
  • 3,731
  • 22
  • 33
  • 46
  • What do you mean by 'Okay'? whether the code should have correct syntax or should be following coding standards or should not contain malicious code? – sv_in Aug 18 '11 at 14:46

3 Answers3

5

Assuming that your need is to check whether the code will not throw any syntax errors, following is my solution:

var code = "asdfsd = 1";

try {
    (function(){
        new Function(code);
    })()
}
catch(e) {
    alert('error');
}

Working Example: http://jsfiddle.net/5NpGa/

sv_in
  • 13,929
  • 9
  • 34
  • 55
  • 2
    `new Function(string)` is `eval` in disguise. – Matt Ball Aug 18 '11 at 14:34
  • 2
    They have their differences. For example, `new Function(str)` doesnt affect the variables in the scope. http://stackoverflow.com/questions/4599857/is-eval-and-new-function-the-same-thing – sv_in Aug 18 '11 at 14:42
  • 2
    Moreover from what i understood, his need was to check if a code will work, not whether it is following coding practices. – sv_in Aug 18 '11 at 14:43
  • 1
    From the OP: _"I have to check if code is OKAY and then window.eval()-it"_. – Matt Ball Aug 18 '11 at 14:45
  • 2
    Be aware that the `catch` in the proposed solution is going to be triggered only in the case of runtime errors (e.g. variable `asdfsd` is not defined). But that code is still syntactically valid. `asdfsd = 1 1` (note the space between the 1s) is not going to be catched. – jotaelesalinas Mar 15 '19 at 14:40
1

You could use a lint library like:

http://www.javascriptlint.com/download.htm

EDIT:

Sorry, that's a compiled linter and you're wanting something for on-the-fly. Try jslint: http://jslint.com

Jonathan M
  • 17,145
  • 9
  • 58
  • 91
1

You're looking for Crockford's jslint.js. It's the same code that powers http://jslint.com/.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710