Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping in eval's argument

Tags:

javascript

I'm using eval to assign dynamic object's properties.

property_name_1 = property1;
property_name_2 = property2;
property_value_1 = 1;
property_value_2 = 2;
var obj = new Object;

eval("obj."+property_name_1+"='"+property_value_1+"'");
eval("obj."+property_name_2+"='"+property_value_2+"'");

then I'm using this object as post data during ajax request.

Everything is ok, but as well known eval is not safe function and I should escape property_value_1, property_value_2. For example, property_value_2 = "<a href=''>Yahoo!</a>" will cause error.

What is the best way to do it?

Thank you

like image 375
Kirzilla Avatar asked Oct 19 '10 11:10

Kirzilla


1 Answers

The best way is to not use eval at all:

obj[property_name_1] = property_value_1;
obj[property_name_2] = property_value_2;

If you still want to, you have to escape apostrophes and backslashes to put the values in string literals:

eval("obj." + property_name_1 + "='" + property_value_1.replace(/\\/g,'\\\\').replace(/'/g,"\\'") + "'");
eval("obj." + property_name_2 + "='" + property_value_2.replace(/\\/g,'\\\\').replace(/'/g,"\\'") + "'");

(If you surround the literal string with quotation marks instead of apostrophes, you have to escape quotation marks and backslashes.)

like image 107
Guffa Avatar answered Sep 25 '22 15:09

Guffa