Javascript转义字符串中的所有单引号 [英] Javascript escape all single quotes in string
本文介绍了Javascript转义字符串中的所有单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将html存储在json中,为此我将html字符串化.
I want to store html in json and for that i stringify the html.
问题是我不能替换所有单引号.
Problem is that I can't replace all single quotes.
这是我的代码:
<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));
}
我还能怎么做?
推荐答案
问题不会被替换,这是JSON.stringify处理反斜杠的方式.因此,如果您在字符串转换后进行替换,它将起作用.
Issue is not replace, it's how JSON.stringify treats a backslash. So if you do your replacement after stringify it'll work.
例如
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>
这篇关于Javascript转义字符串中的所有单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文