Escaping single quotes in JavaScript string for Ja

2019-02-02 03:56发布

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.

4条回答
放荡不羁爱自由
2楼-- · 2019-02-02 04:04

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.

查看更多
祖国的老花朵
3楼-- · 2019-02-02 04:05
strInputString = strInputString.replace(/'/g, "''");
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-02-02 04:07

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
5楼-- · 2019-02-02 04:19

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.

查看更多
登录 后发表回答