Escaping single quotes in JavaScript string for JavaScript evaluation

烂漫一生 提交于 2019-11-30 02:55:14
Nikita Tkachenko

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, "\\'");

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.

Best to use JSON.stringify() to cover all your bases, like backslashes and other special characters:

var strTest = "strResult = " + JSON.stringify(strInputString) + ";";
eval(strTest);
alert(strResult);

Note that it adds its own surrounding double-quotes, so you don't need to include single quotes anymore.

Only this worked for me:

searchKeyword.replace("\'", "\\\'");//searchKeyword contains "d'av"

So, the result variable will contain "d\'av".

I don't know why with the RegEx didn't work, maybe because of the JS framework that I'm using (Backbone.js)

Karthik G
strInputString = strInputString.replace(/'/g, "''");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!