Escaping javascript apostrophe / quotation for eval function, so it still works as a selector?

StackOverflow https://stackoverflow.com/questions/23221926

  •  07-07-2023
  •  | 
  •  

Question

Following js code in a jsfiddle:

JS:

function myFunc(foo){
    $(foo).val("magic, it works!... NOT");    
}

var x = "myFunc('input[name=\\'testme\\']')";


eval (x);

HTML:

<input name="testme" type="text" />

Someone got a clue what I could do?

Was it helpful?

Solution

You need to give this way:

function myFunc(foo){
    $(foo).val("magic, it works!... NOT");    
}

var x = "(myFunc('input[name=\"testme\"]'))";

eval(x);

Combine them inside the (). But you need to also consider this. You need to give in No Wrap (body).

Fiddle: http://jsfiddle.net/praveenscience/243ur/2/

OTHER TIPS

Don't use eval.

In your example, you are passing eval a constant string. This can be replaced with simply the contents of the string. That's all eval is actually doing, except using eval makes it impossible for JavaScript engines to optimise your code.

Your example can be replaced with:

function myFunc(foo){
    $(foo).val("magic, it works!... NOT");
}

myFunc('input[name=\'testme\']');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top