user1170330 user1170330 - 6 months ago 14
Javascript Question

Escape single quotes in title

I want to include a string with single quotes into a title of an image.

myTitle = "abc '' def";
document.write("<img title='" + myTitle + "' src='http://www.example.com/image.png' />")


Here, instead of
abc '' def
only the substring
abc
is displayed. So everything after the single quotes is just removed.

As the title actually comes from a database, I can't just do
\'
, so I need to escape it here
title='" + myTitle + "'
.

Is there a function for that?

Here is a fiddle.

Answer

You can use double quote:

myTitle = "abc '' def";
document.write('<img title="' + myTitle + '" src="http://www.example.com/image.png" />');

or escape the quote:

myTitle = "abc '' def";
document.write("<img title='" + myTitle.replace(/'/g, '&#39;') + "' src='http://www.example.com/image.png' />");