You could use the esprima javascript parser to see if the string is valid javascript syntax.
Install using npm install esprima
.
To use:
var esprima = require('esprima');
var userStringToTest = 'var a = 10;';
var isValid = isValidJs(userStringToTest);
if(isValid) {
console.log('its valid!');
}
else {
console.log('its NOT valid!');
}
function isValidJs(testString) {
var isValid = true;
try {
esprima.parse(testString);
}
catch(e) {
isValid = false;
}
return isValid;
}
As @FelixKing pointed out in his comment, this of course won't detect runtime errors. For your use case though, it sounds like you should be testing for syntax errors as opposed to runtime errors since that is both more strict and there really shouldn't be valid javascript syntax to begin with.