React: How to load an image by path that contains special characters?

Viewed 517

I have tried to load an image by path that contains special characters like &@^.

When I loaded the image as below, it didn't work.

<img src="file:///test/@#$%/0.png"/>

So, I've tried to use encodeURI(path), encodeURIComponent(path), but it didn't work too.

How can I do this?

2 Answers

You have to encode each level in your path (skip the / characters):

const path = 'file:///test/@#$%/0.png'
const encodedPath = 'file://' + path.replace('file://', '').split('/').map((p) => encodeURIComponent(p)).join('/')
console.log(encodedPath)
// Output: file:///test/%40%23%24%25/0.png

Use the above output for your img tag, it will be loaded.

You cannot render them as string. If you want to use them, you must write on Numeric code or JS escape.

You can find their codes from here

As your wanted,

@ : &#64;
# : &#35;
$ : &#36;
Related