I am faced with the task of extracting file names and types from a list of files in an object and displaying them in a table.
The list of files is returned by the server in the format: timestamp_id_filename
.
For example:
1568223848_12345678_some_document.pdf
To achieve this, I created a helper function that processes the string.
Initially, I attempted to use the String.prototype.split()
method with regex to separate the string, but encountered a problem due to files having underscores in their names. This led me to rethink my approach as the original solution was not effective.
The function I developed is as follows:
const shortenString = (attachmentName) => {
const file = attachmentName
.slice(attachmentName.indexOf('_') + 1)
.slice(attachmentName.slice(attachmentName.indexOf('_') + 1).indexOf('_') + 1);
const fileName = file.slice(0, file.lastIndexOf('.'));
const fileType = file.slice(file.lastIndexOf('.'));
return [fileName, fileType];
};
I am now exploring more elegant solutions to extract file names and types without resorting to loops.