Question

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.

Thank you alot, JavaScript Commando's from around the world.

Was it helpful?

Solution

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

OTHER TIPS

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/

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top