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
.
I agree that this
var formattedString = string.replace(/'/g, "\\'");
works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.The solution that worked for me is that you need to put three
\
and escape the double quotes."var string = \"l'avancement\"; var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three
\
was the work around.The thing is that
.replace()
does not modify the string itself, so you should write something like:It also seems like you're not doing character escaping correctly. The following worked for me:
Best to use
JSON.stringify()
to cover all your bases, like backslashes and other special characters:Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.