Javascript Set Attribute with one quote

It looks like javascript by default adds attributes using double quotes. However, in my situation, I am trying to add a json string to the data attribute and the double quote gets in the way of the json.

var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json)); //<div data-json="{"foo":"bar"}">

      

How do I add an attribute using a single quote?

+3


source to share


2 answers


It is wrong to say that

by default javascript adds attributes using double quotes.

An attribute is just a string. The attribute value itself does not include the surrounding quotes. Quotes are nothing more than syntax for representing a string literal. The outer quotes you see around the attribute in



<div data-json="{"foo":"bar"}">

      

does not exist in the attribute value; they were just inserted by the console when it prints out the attribute for your convenience. Nothing gets in the way of JSON. The attribute value can be retrieved and analyzed using JSON.parse

as and without additional ada.

var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json));

// now, parse the attribute
>> JSON.parse(el.getAttribute('data-json'))
<< Object {foo: "bar"}

      

+4


source


I think the best practice is string escaping (see adeneo's answer ).

But just like the other option, you can replace double quotes with single quotes with a function .replace()

:



var json = {"foo":"bar"}

var encoded = JSON.stringify(json);
encoded = encoded.replace(/\\"/g, '"')
    .replace(/([\{|:|,])(?:[\s]*)(")/g, "$1'")
    .replace(/(?:[\s]*)(?:")([\}|,|:])/g, "'$1")
    .replace(/([^\{|:|,])(?:')([^\}|,|:])/g, "$1\\'$2");

var el = document.getElementById("someElement");
el.setAttribute("data-json", encoded);

      

Attention the result string is "{'foo':'bar'}"

not valid json

0


source







All Articles