Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Escaping quotes coming from JSON

I get some data from JSON and put it as a custom attribut data-info into an a-tag. When clicking on this link, the information should appear:

$("#div").append("<a href='#' data-info='" + value.info + "'>" + value.name "</a>");

Unfortunately, JSON may contain some quotes that break my code:

<a href="javascript:void(0)" class="trends" data-wiki="Some "infos" with 'quotes'">Some text</a>

How can I escape all quotes coming from JSON?

Upvotes: 3

Views: 49

Answers (3)

Michał
Michał

Reputation: 905

With jQuery you can use attr

var $link = $('<a href="#" />').text(value.name).attr('data-info', value.info);
$("#div").append($link); 

Upvotes: 1

CoderPi
CoderPi

Reputation: 13211

Here is what you wanted:

$("#div").append("<a href='#' data-info='" + value.info.replace("'", "\'") + "'>" + value.name "</a>");

But you should do it like @Niet the Dark Absol's answer 😉

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

Do it properly.

var a = document.createElement('a');
a.setAttribute("href","#");
a.setAttribute("data-info",value.info);
a.appendChild(document.createTextNode(value.name));
$("#div").append(a);

Done ;)

Upvotes: 3

Related Questions