Kirzilla
Kirzilla

Reputation: 16596

Escaping in eval's argument

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

Upvotes: 5

Views: 5869

Answers (5)

emi
emi

Reputation: 3078

I know this is an old question, but for completeness there is an extra answer not considered before.

With modern JS you can create an object similarly to what @Kalinin wanted to do, but with the desired result (note the [] around properties names):

var obj = {
    [property_name_1]: property_value_1, 
    [property_name_2]: property_value_2
};

Upvotes: 0

Kalinin
Kalinin

Reputation: 2519

I would use the object literal:

var obj = {
    property_name_1: property_value_1, 
    property_name_2: property_value_2
};

Upvotes: -1

Guffa
Guffa

Reputation: 700720

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.)

Upvotes: 6

ArtBIT
ArtBIT

Reputation: 3999

Try:

var obj = new Object();
obj[property_name] = property_value;

Upvotes: 0

mhitza
mhitza

Reputation: 5715

Is eval really needed?

Based on your example you could simply do:

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

If this isn't a solution for you for whatever reason, go on about escaping quotes with \.

Upvotes: 0

Related Questions