Javascript转义字符串中的所有单引号

时间:2017-11-02 13:47:22

标签: javascript jquery json string

我想在json中存储html,为此我将字符串化为html。

问题是我无法替换所有单引号。

这是我的代码:

<div id="myHtml">Men's and Women's something.</div>

和js:

function save(){
    item = {}
    dataTemplate = []
    item['html'] = $('#myHtml').html().replace(/'/g,"\'"); // not working
    // tried with .replace(/'/g,"\\'"); but I don't want two \\
    // this is broken .replace(/'\/g,"\\'")
    dataTemplate.push(item);
    alert(JSON.stringify(dataTemplate));
}

我还能怎么做?

2 个答案:

答案 0 :(得分:1)

问题不会被替换,这是JSON.stringify处理反斜杠的方式。因此,如果您在字符串转换后进行替换,它将起作用。

例如

function save(){
    item = {}
    dataTemplate = []
    item['html'] = $('#myHtml').html();
    dataTemplate.push(item);
    a = JSON.stringify(dataTemplate);
    a = a.replace(/'/g,"\\'");
    //alert(a);
    console.log(a);
}

save();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div id="myHtml">Men's and Women's something.</div>

答案 1 :(得分:0)

replace()替换所有符号或部分字符串使用函数RegExp()

像这样:

&#13;
&#13;
function save(){
    item = {}
    dataTemplate = []
    item['html'] = $('#myHtml').html().replace(new RegExp("'","g"), "");
    console.log(item);
}

 save();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div id="myHtml">Men's and Women's something.</div>
&#13;
&#13;
&#13;