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

Time:01-19

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?

CodePudding user response:

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

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

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

CodePudding user response:

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;
  •  Tags:  
  • Related