JSON.stringify
uses "
as default line separators. Just data-photo
enclose the attribute value in quotation marks '
instead of "
quotation marks:
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>`;
Note 1: One of the advantages of using Template Literals is that you can use ${}
syntax instead + ... +
.
Note 2: If the properties of an object photo
can contain a quote '
, as in:
var photo = {id: 5, name: "I'm here.jpg", alt: ""};
then you have to avoid it like this :
JSON.stringify(photo).replace(/'/g, "&
// ^^^^^^^^^^^^^^^^^^^^^^^ replace all single quotes with their escaped values
by following this last method, you can keep the double quotes as in the code in the question, but avoiding the double quotes this time:
var res = `
<a href="#" id="edit-image"
data-toggle="modal"
data-target="#modal-edit-image"
data-photo="${JSON.stringify(photo).replace(/"/g, """)}"
// ^ 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
source
to share