'HTML can't properly read unicode in image tag src

I am using electron with html, css and js. For my desktop app, I want to import an image from my local storage using an img tag. However, my file name contains an unicode (e.g. #). When, HTML try to fetch the image it gets rid of the second half part of the file name starting from the unicode.See the example below please.

<img src= "path/to/my/example#file.png">

This becomes, src= "path/to/my/example"

by deleting the part after the Unicode. Returning me ERR_FILE_NOT_FOUND in console.

using %23 may be an option however, The filename is unfortunately unpredictable and it changes based on the file (I import several pictures). So, obtaining the filename and creating the HTML tag is automized using javascript. Is there a way for the javascirpt to automatically catch unicode in a string (path to file) and enforce it so that html can read it?



Solution 1:[1]

# is not a "unicode" as you call it. It is just a plain ASCII character. But, within a url, it just happens to be a reserved character, used to denote an anchor within a resource, and so is not part of the resource's path, which is why you see it getting stripped off.

So, you must url-encode (ie, percent-encode) the # character as %23 if it is meant to be used inside the path itself, eg:

<img src="path/to/my/example%23file.png">

Since you said that you need to generate this HTML via JavaScript, you will need to have your script parse the file path and encode any reserved characters as needed. In fact, JavaScript has built-in functions for this exact purpose: encodeURI() and encodeURIComponent().

Solution 2:[2]

You need to 'url encode' also known as 'percent encode' all special characters. In your example, replace the # with %23.

You also incorrectly used : instead of = in the attribute:

<img src="path/to/my/example#file.png">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lebeau
Solution 2 Evert