In Javascript, How Can I Extract The Name Of An Image File From A Long String?
Can you help to extract the file name from this string? let str = 'https://s3.amazonaws.com/test/testSite/product/image_folder/Z1-00034-01/1623934721778.jpeg%25253FX-Amz-Algorithm%
Solution 1:
Not sure why you're getting a triple escaped URL, but you can fix that like this:
let str = "https://s3.amazonaws.com/test/testSite/product/image_folder/Z1-00034-01/1623934721778.jpeg%25253FX-Amz-Algorithm%25253DAWS4-HMAC-SHA256%252526X-Amz-Date%25253D20210722T050758Z%252526X-Amz-SignedHeaders%25253Dhost%252526X-Amz-Expires%25253D599%252526X-Amz-Credential%25253DAKIA4Z2VUPBRCPYFDP4G%2525252F20210722%2525252Fus-east-1%2525252Fs3%2525252Faws4_request%252526X-Amz-Signature%25253D259df0ed0fd8f827e74c612ff8d87e65e2f2c8d68f75a2f06eb71a84de3847a1%253FX-Amz-Algorithm%253DAWS4-HMAC-SHA256%2526X";
const url = newURL(unescape(unescape(unescape(str))));
const filename = url.pathname.split('/').pop();
console.log(filename)
Solution 2:
Assuming you always wanted to target a JPEG file, you could use match
here:
let str = "https://s3.amazonaws.com/test/testSite/product/image_folder/Z1-00034-01/1623934721778.jpeg%25253FX-Amz-Algorithm%25253DAWS4-HMAC-SHA256%252526X-Amz-Date%25253D20210722T050758Z%252526X-Amz-SignedHeaders%25253Dhost%252526X-Amz-Expires%25253D599%252526X-Amz-Credential%25253DAKIA4Z2VUPBRCPYFDP4G%2525252F20210722%2525252Fus-east-1%2525252Fs3%2525252Faws4_request%252526X-Amz-Signature%25253D259df0ed0fd8f827e74c612ff8d87e65e2f2c8d68f75a2f06eb71a84de3847a1%253FX-Amz-Algorithm%253DAWS4-HMAC-SHA256%2526X";
filename = str.match(/\b[^/\s]+\.(?:jpeg|png)/)[0];
console.log(filename);
Solution 3:
let str = "https://s3.amazonaws.com/test/testSite/product/image_folder/Z1-00034-01/1623934721778.jpeg%25253FX-Amz-Algorithm%25253DAWS4-HMAC-SHA256%252526X-Amz-Date%25253D20210722T050758Z%252526X-Amz-SignedHeaders%25253Dhost%252526X-Amz-Expires%25253D599%252526X-Amz-Credential%25253DAKIA4Z2VUPBRCPYFDP4G%2525252F20210722%2525252Fus-east-1%2525252Fs3%2525252Faws4_request%252526X-Amz-Signature%25253D259df0ed0fd8f827e74c612ff8d87e65e2f2c8d68f75a2f06eb71a84de3847a1%253FX-Amz-Algorithm%253DAWS4-HMAC-SHA256%2526X";
var patt1 = /[\w&.-]+\.([0-9a-z]+)(?:[\?#%]|$)/i;
var matches= str.match(patt1);
let filename = matches[0].split(".")[0] + '.' +matches[1]
console.log(matches)
console.log(filename)
//EDITvar patt2 = /([\w&.-]+)\.([0-9a-z]+)(?:[\?#%]|$)/i;
var matches= str.match(patt2);
let filename2 = matches[1] + '.' +matches[2]
console.log(matches)
console.log(filename2)
[\w&.-]
- Matches FileName. If you change[\w&.-] to [/\/\w&.-]
it will match all characters except https://[0-9a-z]
- This one matches extension[\?#%]
- Here you can add special characters to be removed- $ symbol will match last words
- /i - ignore case in the given string
([\w&.-]+) and ([0-9a-z]+)
will match filename and extension seperate
Post a Comment for "In Javascript, How Can I Extract The Name Of An Image File From A Long String?"