[Vuejs]-How to truncate multiple lines while showing strings at the end?

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 a file 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 the name property of the file object.

  • The fileExtension variable is extracted by splitting the fileName using the dot (".") as the delimiter and selecting the last element.

  • The fileNameWithoutExtension variable is obtained by removing the file extension from the fileName. It uses the substring 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 the fileNameWithoutExtension.

  • If the length of the truncatedName exceeds the maximum allowed characters, a truncation is performed. The truncatedCharacters 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. The substring method is then used to truncate the truncatedName 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;
}

Leave a comment