I want to remove white space from an object field so I can display it as a background image in CSS using JSX.
renderImage(singleMedia, type) {
let mediaType = singleMedia.mediaType;
if(type == "image")){
var mediaPreview = singleMedia.mediaPreview.replace(/\s+/g, '%20');
console.log("The original image was", singleMedia.mediaPreview, "The NEW ONE IS", mediaPreview);
var divStyle = {
backgroundImage: 'url(' + mediaPreview + ')'
}
}
return(
<div className="image-logo" style={divStyle}> </div>
);
}
I can render the image fine if mediaPreview has NO spaces. But when it does have a space, I still can't view it even after I add the %20.
When I run my code I get the following results: (But the output is still blank. The image only shows if I send one with no white space)
the original image was http://api.testing.ca/media/ad/no-smoking-sign (1).png The NEW ONE IS http://api.testing.ca/media/ad/no-smoking-sign%20(1).png
I'm wondering if there's a way to strip the white space and convert it to %20 within the divStyle?
The problem is not the whitespace, the problem is the end-parenthesis in the file name. Instead of replacing white space with %20 instead replace ) with %29:
var mediaPreview = singleMedia.mediaPreview.replace(/\)/g, '%29');
The url token in CSS ends when the first non-escaped ) is found.
Alternatively, you can quote the entire URL:
var divStyle = {
backgroundImage: 'url("' + mediaPreview + '")'
}
but then you would need to escape quotes instead.