How to find out syntax error of a single line JavaScript code?
Asked Answered
C

1

6

Say, there is a text box. User written the following code:

document.getElementById("id").;

It will surely cause some syntax error.

There is also a "RUN" button. my requirement is :

if user click on that button, the code written in the text box should be validated that it is syntactically correct. If it is syntactically incorrect then a alert should be raised that "Incorrect Syntax". I need not to display where is the error. just to check whether the code is syntactically correct or not ?

How can I implement this?

Caskey answered 12/1, 2011 at 11:46 Comment(0)
P
2

You can execute the code from the text box using eval, and wrap that in a try/catch. Something like this (I'm just hard coding it here for convenience):

try
{
    eval('document.getElementById("id").;');
}
catch(e)
{
    console.log(e);
    //show your own custom error message or something...
}

Results in: SyntaxError: syntax error

Proviso answered 12/1, 2011 at 11:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.