Escaping single quotes in JavaScript string for JavaScript evaluation

Florian Mertens picture Florian Mertens · Feb 26, 2013 · Viewed 109.6k times · Source

I have a project, in which some JavaScript var is evaluated. Because the string needs to be escaped (single quotes only), I have written the exact same code in a test function. I have the following bit of pretty simple JavaScript code:

function testEscape() {
    var strResult = "";
    var strInputString = "fsdsd'4565sd";

    // Here, the string needs to be escaped for single quotes for the eval 
    // to work as is. The following does NOT work! Help!
    strInputString.replace(/'/g, "''");

    var strTest = "strResult = '" + strInputString + "';";
    eval(strTest);
    alert(strResult);
}

And I want to alert it, saying: fsdsd'4565sd.

Answer

Nikita Tkachenko picture Nikita Tkachenko · Feb 26, 2013

The thing is that .replace() does not modify the string itself, so you should write something like:

strInputString = strInputString.replace(...

It also seems like you're not doing character escaping correctly. The following worked for me:

strInputString = strInputString.replace(/'/g, "\\'");