最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Set Attribute With Single Quotation - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

It 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

发布评论

评论列表(0)

  1. 暂无评论