Evgenij Reznik
Evgenij Reznik

Reputation: 18594

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.

Upvotes: 2

Views: 2630

Answers (5)

Seyed Morteza Hosseini
Seyed Morteza Hosseini

Reputation: 402

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' />")

Upvotes: 2

Vladimir Drenovski
Vladimir Drenovski

Reputation: 300

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.

Upvotes: 1

jcubic
jcubic

Reputation: 66560

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' />");

Upvotes: 6

Mojtaba
Mojtaba

Reputation: 5002

A simple replace:

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

Upvotes: 1

SparK
SparK

Reputation: 5211

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;.

Upvotes: 0

Related Questions