Adrian
Adrian

Reputation: 523

Javascript escape all single quotes in string

I want to store html in json and for that i stringify the html.

Problem is that I can't replace all single quotes.

This is my code:

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

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

How else can I do it?

Upvotes: 1

Views: 7016

Answers (1)

Amit
Amit

Reputation: 15

Issue is not replace, it's how JSON.stringify treats a backslash. So if you do your replacement after stringify it'll work.

For e.g.

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>

Upvotes: 1

Related Questions