2

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.

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

5 Answers5

6

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' />");
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • If they switch around the single quotes and double quotes in their JavaScript code, they just end up with the same problem when their string contains double quotes, not single quotes. Escaping them is the better option. – Anthony Grist May 19 '16 at 14:08
2

you can solve your problem by replace all single quotes with its html entity.

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

A simple replace:

myTitle = "abc '' def";
myTitle = myTitle.replace(/'/g, "\\'");
document.write("<img title='" + myTitle + "' src='http://www.example.com/image.png' />")
Mojtaba
  • 4,852
  • 5
  • 21
  • 38
  • This won’t work if a single quote is already prefixed by a backslash: `"foo \\'' bar".replace(/'/g, "\\'")` gives `"foo \\'\' bar"`. – bfontaine May 19 '16 at 14:02
1

you just need to exchange the double quotation with single quotation in your string representations of html code like such :

myTitle = "abc '' def";

document.write('<img title="' + myTitle + '" src="https://www.google.de/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" />')

Here's a JSFiddle

And here's a Diffchecker

The way you wrote it makes it so that the code brakes at the first single quotation in the title string because it follows another single quotation.

Community
  • 1
  • 1
  • What do they do if they have double quotes, rather than single quotes, in their title after switching to use your code? What do they do if they have **both**? – Anthony Grist May 19 '16 at 14:09
0

You can try html-entity-encoding your string as seen in this answer: https://stackoverflow.com/a/18750001/773259

That will scape your single quotes to its unicode values &#39;.

Community
  • 1
  • 1
SparK
  • 5,181
  • 2
  • 23
  • 32