admin管理员组文章数量:1425735
It seems that by default javascript appends attributes using double quotes. However in my situation I am attempting to append a json string to a data attribute and the double quote interferes with the json.
var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json)); //<div data-json="{"foo":"bar"}">
How can I append an attribute using a single quote?
It seems that by default javascript appends attributes using double quotes. However in my situation I am attempting to append a json string to a data attribute and the double quote interferes with the json.
var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json)); //<div data-json="{"foo":"bar"}">
How can I append an attribute using a single quote?
Share Improve this question asked Apr 20, 2015 at 2:09 ryandlfryandlf 28.6k37 gold badges111 silver badges164 bronze badges2 Answers
Reset to default 6It is incorrect to say that
by default javascript appends attributes using double quotes.
An attribute is merely a string. The attribute value itself does not include the surrounding quotes. Quotes are nothing more than syntax for representing a string literal. The outside quotes you see surrounding the attribute in
<div data-json="{"foo":"bar"}">
do not exist in the attribute value; they were simply inserted by the console when it is printing out the attribute for your visual convenience. There is nothing "interfering with the JSON". The attribute value can be retrieved and parsed with JSON.parse
as is with no further ado.
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"}
I think the better practice is string escaping (see adeneo's answer).
But just as an other option you may be able to replace double quotes with single quotes by .replace()
function:
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 "{'foo':'bar'}"
is not a valid json
本文标签: Javascript Set Attribute With Single QuotationStack Overflow
版权声明:本文标题:Javascript Set Attribute With Single Quotation - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745364977a2655469.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论