0👍
I’m not 100% sure, but to achieve this bahavior of displaying file names within a character limit while ensuring the file extension is always visible, you can follow this approach:
const handleName = (file) => {
const MAX_CHARACTERS_ALLOWED = 20; // Adjust this value based on your needs
const fileName = file.name;
const fileExtension = fileName.split('.').pop();
const fileNameWithoutExtension = fileName.substring(0, fileName.length - fileExtension.length - 1);
let truncatedName = fileNameWithoutExtension;
if (truncatedName.length > MAX_CHARACTERS_ALLOWED) {
const truncatedCharacters = MAX_CHARACTERS_ALLOWED - 4 - fileExtension.length;
truncatedName = `${truncatedName.substring(0, truncatedCharacters)}....${fileExtension}`;
}
return truncatedName;
};
Explanation
-
The
handleName
function takes afile
object as input and returns the modified filename. -
The
MAX_CHARACTERS_ALLOWED
variable represents the maximum number of characters allowed for the displayed filename (excluding the file extension). You can adjust this value based on your requirements. -
The
fileName
variable stores the full filename obtained from thename
property of thefile
object. -
The
fileExtension
variable is extracted by splitting thefileName
using the dot (".") as the delimiter and selecting the last element. -
The
fileNameWithoutExtension
variable is obtained by removing the file extension from thefileName
. It uses thesubstring
method with the length of the filename minus the length of the file extension minus 1 to exclude the dot. -
The
truncatedName
variable is initialized with thefileNameWithoutExtension
. -
If the length of the
truncatedName
exceeds the maximum allowed characters, a truncation is performed. ThetruncatedCharacters
variable calculates the available characters for truncation by subtracting 4 (for the "…" ellipsis) and the length of the file extension from the maximum allowed characters. Thesubstring
method is then used to truncate thetruncatedName
to the calculated length and append the file extension with "…" at the end. -
The modified filename is returned by the function.
HTML:
<div class="filename-wrap">
<p>{{ handleName(item) }}</p>
</div>
CSS:
.filename-wrap {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.filename-wrap p {
color: #fff;
margin: auto;
font-size: 14px;
padding: 5px 8px;
overflow-wrap: break-word;
}
- [Vuejs]-How to use onMounted to do async things in Nuxt 3
- [Vuejs]-Getting '400 (Bad Request)' error when making a POST request to backend API