user1170330 user1170330 - 1 year ago 108
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='' />")

Here, instead of
abc '' def
only the substring
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 Source

You can use double quote:

myTitle = "abc '' def";
document.write('<img title="' + myTitle + '" src="" />');

or escape the quote:

myTitle = "abc '' def";
document.write("<img title='" + myTitle.replace(/'/g, '&#39;') + "' src='' />");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download