Madhav
Madhav

Reputation: 569

how to encode single quote/apostrophe in jquery?

here I am trying to encode single quote/apostrophe which i have to bind to an image as an alternate text.
I am trying to encode it because while I have apostrophe or single quote in string as like this is image's alternate text
and I am binding it to image tag from jquery itself then after binding it shows alt text as
alt="this is image"s alternate text"
where it's has to be displayed like
alt="this is image's alternate text"
my code is as below.

var alternateText = "this is image's alternate text";
var URL = "Image url"
var r = "<div><a class='popup'><img src='" + URL + "' class='img-responsive 'alt='" + alternateText + "></a></div>";
$("div#div1").html(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>

Upvotes: 0

Views: 970

Answers (2)

Satpal
Satpal

Reputation: 133403

You should use jQuery method jQuery( html, attributes ) to create element, it will save you from quotes mess.

var alternateText = "this is image's alternate text ";
var URL = "Image url"

var img = $('<img>', {
  "src": URL,
  "alt": alternateText,
  "class": "img-responsive"
});
$("#div1").html(img);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>

Upvotes: 2

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18113

Maybe I'm looking at this to easy, but why not change the quotes in the HTML to double quotes...

var alternateText ="this is image's alternate text";
var URL ="Image url"
var r= '<img src="' + URL + '" class="img-responsive" alt="' + alternateText + '">';
$("div#div1").html(r);

Or escape the quote

var alternateText = 'this is image\'s alternate text';
var URL ="Image url"
var r="<img src='" + URL + "' class='img-responsive ' alt='" + alternateText + ">" ;
$("div#div1").html(r);

Or look at this question:

Escape Single and Double Quotes - JQuery or Javascript

Upvotes: 0

Related Questions