3

My code like this :

<script>
var res = `
        <a href="#" id="edit-image"
           data-toggle="modal"
           data-target="#modal-edit-image"
           data-photo="`+JSON.stringify(photo)+`" 
        >
            <span class="fa fa-pencil"></span>
        </a>`;                                                 
</script>

The result of console.log(photo) like this :

Object {id: 5, name: "IMziQFBIxFEFQHdjlg3mGXEVuQnwqZ5rYigX2jlq.jpeg", alt: "dea"}

I want to change it to json string and save it in variable res

I do it like above code, but if I inspect element and I copy the element the result like this :

<a href="#" id="edit-image" data-toggle="modal" data-target="#modal-edit-image" data-photo="{" id":5,"name":"imziqfbixfefqhdjlg3mgxevuqnwqz5ryigx2jlq.jpeg","alt":"dea"}"="">
    <span class="fa fa-pencil"></span>
</a>

It seems json stringfy in the element untidy

How can I solve it?

moses toh
  • 12,344
  • 71
  • 243
  • 443

1 Answers1

1

JSON.stringify uses " as default string delimiters. Just wrap the value of the data-photo attribute in ' quotes instead of " quotes:

var res = `
    <a href="#" id="edit-image"
        data-toggle="modal"
        data-target="#modal-edit-image"
        data-photo='${JSON.stringify(photo)}'
    //             ^ here                   ^ and here
    >
        <span class="fa fa-pencil"></span>
    </a>`;

Note 1: One of the benefits of using Template Literals is that you can use ${} instead of the + ... + syntax.

Note 2: If the properties of the object photo could have a ' quote in them as in:

var photo = {id: 5, name: "I'm here.jpg", alt: ""};
//                         ^^^

then you'll have to escape it like this:

JSON.stringify(photo).replace(/'/g, "&#39;")
//                   ^^^^^^^^^^^^^^^^^^^^^^^ replace all single quotes with their escaped values

following this last method, you can keep double quotes as in the code in the question, but this time escaping double quotes instead:

var res = `
    <a href="#" id="edit-image"
        data-toggle="modal"
        data-target="#modal-edit-image"
        data-photo="${JSON.stringify(photo).replace(/"/g, "&#34;")}"
    //             ^ here                                          ^ and here
    // use double quotes to surround the value of data-photo and excape " in the result of JSON.stringify
    >
        <span class="fa fa-pencil"></span>
    </a>`;
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73