在JavaScript字符串中转义单引号以进行JavaScript评估 [英] Escaping single quotes in JavaScript string for JavaScript evaluation

查看:57
本文介绍了在JavaScript字符串中转义单引号以进行JavaScript评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其中评估了一些JavaScript var。因为字符串需要转义(仅限单引号),所以我在测试函数中编写了完全相同的代码。我有以下一些非常简单的JavaScript代码:

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);
}

我想提醒它,说: fsdsd '4565sd

推荐答案

事情是 .replace()不会修改字符串本身,所以你应该写如下:

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

这篇关于在JavaScript字符串中转义单引号以进行JavaScript评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆