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

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

Leave a Comment