Reputation: 18594
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?
Upvotes: 2
Views: 2630
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, "'") + "' src='http://www.example.com/image.png' />")
Upvotes: 2
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
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, ''') + "' src='http://www.example.com/image.png' />");
Upvotes: 6
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
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 '
.
Upvotes: 0