CSS and JQuery: spaces inside image name break code of url()

心不动则不痛 提交于 2019-11-28 00:57:19

Spaces are not valid in a URI. They need to be encoded to %20.

You could src.replace(/ /g, '%20'), or more generally, encodeURI(src) to %-encode all characters that aren't valid in a URI. encodeURIComponent(src) is more common, but it would only work if the src was just a single relative filename; otherwise, it'd encode / and stop paths working.

However, the real problem is that the original img src is already broken and only working thanks to browser fixups correcting your error. You need to fix the Ruby script generating the page. You should be URL-encoding the filename before including it in the path; there are many more characters that can cause you problems than just space.

As Pekka said, you should also use quotes around the URL in the url(...) value. Whilst you can get away without them for many URLs, some characters would have to be \-escaped. Using double-quotes mean you can avoid that (no double-quotes can appear in a URL itself).

Adding quotes around the URL should help:

  $('#viewlarge').css('backgroundImage','url("' + src +'")'); 

however, according to the W3C specs, white space must be escaped, so the URL encoding solution provided by @Andy E's head @bobince is the safest one.

  • Firstly, why are you letting clients determine the name of your images?
  • Secondly, why aren't you sanitizing them?
  • Thirdly, i suspect you aren't urlencoding the urls when you write them to the html (which would turn a space into a %20)

Use Javascript encode function to encode your 'src'

E.g.

$('#viewlarge').css('backgroundImage','url(' + encode(src) +')'); 

I think you can also use Javascript 'escape' function as well

$('#viewlarge').css('backgroundImage','url(' + escape(src) +')');

I know you've already selected your answer, but I want to improve Pekka's solution and provide the most feasible solution because I ran into another problem while it's handling a file name with brackets.

$("#viewlarge").css("background",'url(' + "'" + url+ "'" + ')');

I hope it helps !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!