'Javascript encodeURI not work well with csv
I'm trying generate short CSV by the code bellow :
Source
const csv_content = `"Hello"þ"World"þ"#"þ"123"`;
const href = 'data:attachment/csv;charset=utf-8,' + encodeURI(csv_content);
console.log(href);
I copy/past the href value in my browser and download it.
Value of href
data:attachment/csv;charset=utf-8,%22Hello%22%C3%BE%22World%22%C3%BE%22#%22%C3%BE%22123%22
I open it in Excel but I can't show any chars after # char and the # itself. If someone can explain me why encodeURI and # return me this issue, that would be wonderfull !
SOLUTION
evolutionxbox
comment resolve this issue, you need use encodeURIComponent instead encodeURI
// encodes characters such as ?,=,/,&,:
console.log(`?x=${encodeURIComponent('test?')}`);
// expected output: "?x=test%3F"
Solution 1:[1]
SOLUTION
evolutionxbox
comment resolve this issue, you need use encodeURIComponent instead encodeURI
// encodes characters such as ?,=,/,&,:
console.log(`?x=${encodeURIComponent('test?')}`);
// expected output: "?x=test%3F"
Solution 2:[2]
Your issue actually touches on an important topic, and that is what should be passed in a URL vs what should be passed in the body.
When you get to complex objects, like a csv file, it would be best to use the body to hold this information, as it is much less picky about characters.
Another reason is that the URL is open and unprotected information. If you ever made a csv file that contained sensitive data, anybody in the world can see it. Data in the body (assuming you are using https) is encrypted and not open to all viewers.
It is also important to remember the correct uses for GET
, PUT
, PATCH
, DELETE
and POST
. When working with sending a file I would be hard pressed to find a good reason to use GET
as the requestor (if the requestor is the one sending the csv file), the only one of the above where it breaks convention to send data in the body of the request. It is perfectly okay to have data in a GET
response body though.
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 | Adrien Villalonga |
Solution 2 | Jeff B |