shkurta
shkurta

Reputation: 131

Decoding url not working properly JS I tried decodeURIComponent

Hi I have a case a URL simillar to this:

https://linkhere?response-content-disposition=inline; filename="placeholder.jpg"; filename*=UTF-8''placeholder.jpg  response-content-type=image/jpeg&X-Amz-Algorithm=....sometextcontinueshere

I am trying to decode it like this and I need to take the filename

  const decodedUrl = decodeURIComponent("linkhere")
  
  const urlParams = new URLSearchParams(decodedUrl);
  const filename = urlParams.get('filename');
  console.log(decodedUrl) 

But for some reason does not work the decoding properly, do you guys have any idea?

Upvotes: 1

Views: 74

Answers (1)

epascarello
epascarello

Reputation: 207501

There is nothing built in that is magically going to get the filename since it is not a querystring paramter. The easiest thing you can do it change whatever is building this to have valid querystring parameters so you can parse it.

With what you have, you will need to read the one parameter that has the file name in it. After that you are going to have to parse out the filename from that string.

Basic idea:

var str = `https://linkhere?response-content-disposition=inline; filename="placeholder.jpg"; filename*=UTF-8''placeholder.jpg  response-content-type=image/jpeg&X-Amz-Algorithm=....sometextcontinueshere`;

const url = new URL(str);
const parts = url.searchParams.get('response-content-disposition').split(/;\s/);
const fileNameParam = parts.find(x => x.startsWith('filename=')).match(/"([^"]+)"/)[1];
console.log(fileNameParam);

Upvotes: 2

Related Questions