Easy way to validate / validate javascript syntax

I have a large set of various javascript fragments (several thousand), and some of them have some silly syntax errors (for example, unmatching braces / quotes, HTML inside javascript, typos in variable names).

I need an easy way to check JS syntax. I tried JSLint, but it sends too many warnings about style, how variables are defined, etc. (Even if I turn off all flags). I donโ€™t need to figure out style problems or improve javascript quality, I just need to find obvious syntax errors. Of course, I can just check it in the browser / browser, but I need to do this automatically, since the number of these fragments is large.

Add:
JSLint / JSHint reports many problems in lines that are not โ€œbeautyโ€ but work (that is, they have problems with potential ones ) and cannot see real problems where a regular compiler simply reports a syntax error and stops execution. For example, try JSLint that code that has syntax errors in line 4 (inconsistent quotes), line 6 (requires a comma) and line 9 (unexpectedly <script>).

document.write('something'); a = 0; if (window.location == 'http://google.com') a = 1; document.write("aaa='andh"+a+"eded"'); a = { something: ['a'] something2: ['a'] }; <script> a = 1; 
+6
source share
5 answers

I found that SpiderMonkey has the ability to compile a script without executing it, and if compilation failed, it prints an error.

So, I created a small wrapper for SpiderMonkey

 sub checkjs { my $js = shift; my ( $js_fh, $js_tmpfile ) = File::Temp::tempfile( 'XXXXXXXXXXXX', EXLOCK => 0, UNLINK => 1, TMPDIR => 1 ); $| = 1; print $js_fh $js; close $js_fh; return qx(js -C -f $js_tmpfile 2>&1); } 

And javascriptlint.com also works very well in my case. (Thanks @rajeshkakawat).

+1
source

You can try JSHint , which is less verbose.

+2
source

Just in case anyone else is watching, you can try Esprima ,

It only checks the syntax, nothing more.

+1
source

Lots of options if you have an exhaustive list of JSLint errors that you make .

The JSLint code is actually pretty good and pretty easy to understand (I assume you already know JavaScript well from your question). You can hack it to check only what you want and continue, no matter how many errors it finds.

You can also quickly write something in Node.js to use JSLint as-to to quickly check each file / fragment and output only the errors you care about.

0
source

Semantic Designs (my company) JavaScript formatter reads JS files and formats them. You do not want to format the part.

To read the files that it will format, it uses a full JavaScript parser, which performs a full syntax check (even inside regular expressions). If you run it and just ignore the formatted result, you get a syntax check.

You can give it a large list of files, and it will format them all. You can use this to batch check your large set. (If there are any syntax errors, it returns a non-zero error status to the shell).

-1
source

All Articles