0

I am getting data from database that has single quotes in it. There are no problems in getting that, I get variable with single quotes in it

ex:

var title="vicky's blog";

Now the problem is I am not able to append this variable as title for anchor tag.

I have tried using escape, unescape, replacing with regex and all that. I think i am missing out something, please help.

http://jsfiddle.net/vigneshvdm/mtXSZ/

Please refer to this jsfiddle. Inspect the anchor tag there its not having the full variable as title.

I also tried solutions provided in

Using JavaScript single and double quotes for href's

jQuery single quote in JSON response

Community
  • 1
  • 1
Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150

4 Answers4

4

You need to wrap the title value inside "" in the html element

$("#testing").html('<a href="#" title="'+unescape(title)+'">hello</a>');

Demo: Fiddle

But I would recommend

var title="vicky's blog's test dd \" with";

$('<a />', {
    href: '#', 
    title: title,
    html: 'test'
}).appendTo('#testing')

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks a lot Arun The problem with second solution is that i have the anchor tag in the middle of variable like that variable will be having some tr td etc before and after this anchor tag Anyway thanks a lot :) – Vignesh Subramanian Jun 17 '13 at 04:25
2

Just create the anchor with jQuery and let it solve the escaping issue:

var $anchor = $('<a>', {
    href: '#',
    title: title,
    text: 'hello'
});
$('#testing').html($anchor);

Demo

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

If you want to put text in html you should always html encode the special characters.

'"<>&

var title="vicky&apos;s blog";
Community
  • 1
  • 1
Musa
  • 96,336
  • 17
  • 118
  • 137
0

See this i think it will help you: enter image description here