Csaba Gabor wrote on 03 nov 2009 in comp.lang.javascript:
A string like?
str = "alert(11);{alert('alert(11); is correct Javascript');};"
Would that be usefull?
I don't think it would.
Csaba Gabor wrote on 03 nov 2009 in comp.lang.javascript:
A string like?
str = "alert(11);{alert('alert(11); is correct Javascript');};"
Would that be usefull?
I don't think it would.
You've made a good example, and yes it can be useful.
But I think I better give context to my question
and recast it, especially in light of the fact that my
proposed solution does not work across browsers.
The question arose in the following context: The
user is asked to enter some javascript statements
to affect a value. I want to ensure that all the
statements are syntactically correct, AND to insert
a return before the last statement, if it doesn't
start with return, but does make syntactic sense.
The validation is fairly straightforward:
function syntax_check(code) {
// returns false is code is not syntactically OK
// returns browser's interpretation of the code if it's OK
try {
var f = new Function(code);
return f.toString(); }
catch (err) { return false; } // syntax error
}
On firefox, the returned string is cleaned of all
comments, and is recast into a 'standard form'.
I was thinking that if the penultimate line of
this returned string did not consist of "}",
then a return could be prefixed, if it wasn't
already there. Any exceptions to this?
However, with IE the returned string is not gussied up
into standard form and is left pretty much as is.
So the question, exercise, or problem is: given
a function which will tell you whether or not you
have a syntactically correct javascript, can you
semi reasonably isolate the last statement to
determine whether it should be prefixed with a
return, and to do so in such case.
Some examples:
code = "'Fred'" => return 'Fred';
code = "var i=7; i *= 9"; =>
var i=7;
return i *= 9;
code = "x='word'\nx+='s' // making a plural\n" +
" return x /* pluralizing a word */";
=> no change
Evertjan's code =>
alert(11);
return alert('alert(11); is correct Javascript');
code = '{a = 1; b = 2}' =>
a = 1;
return b = 2;
Two problem cases:
code = "var y=6;\n y*= 2 // difficult; hard case";
code = "var y=6;\n y*= 2; // difficult; hard case";