最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Escape single quotes in title - Stack Overflow

programmeradmin2浏览0评论

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

myTitle = "abc '' def";
document.write("<img title='" + myTitle + "' src='.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 es 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.

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./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 es 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.

Share Improve this question asked May 19, 2016 at 13:53 Evgenij ReznikEvgenij Reznik 18.6k42 gold badges115 silver badges191 bronze badges 2
  • 1 you should not be using document.write create an element and set its attributes. – Daniel A. White Commented May 19, 2016 at 13:55
  • Like said above or if for some reason(???) you want to use document.write, use as string outerHTML of element – A. Wolff Commented May 19, 2016 at 14:04
Add a ment  | 

5 Answers 5

Reset to default 6

You can use double quote:

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

or escape the quote:

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

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

A simple replace:

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

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.

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

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

发布评论

评论列表(0)

  1. 暂无评论