What is the best way to cut off multiple lines of text and display the remaining strings at the

Currently, I am working on a project that involves implementing a gallery feature. The challenge lies in displaying file names which can be quite lengthy, and we are restricted to showing only 2 lines of text. While this can be achieved using line clamp and overflow, the additional requirement to always display the file extension at the end poses an issue.

Instead of displaying:

longfilename_long
filename_longfi..

The desired output should look like:

longfilename_long
filename_....jpg

I attempted a simpler approach by truncating the file name to a certain number of characters and appending the file extension at the end with the following function:

const handleName = (file: File) => {
  let fileName = '';
  const fileExtension = file.name.split('.').pop();

  file.name.length > LIMIT_CHAR
      ? (fileName = `${file.name.substring(0, MAX_CHARACTERS_ALLOWED - fileExtension.length - 1)}....${fileExtension}`)
      : (fileName = file.name);
  return fileName;
};
<div class="filename-wrap">
    <p>{{ handleName(item) }}</p>
</div>
.custom-delete-label-isShow {
       margin: auto;
       height: 105px;
       .filename-wrap {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;

            p {
               color: #fff;
               margin: auto;
               font-size: 14px;
               padding: 5px 8px;
               overflow-wrap: break-word;
            }
       }
}

However, this method sometimes results in long, breakable substrings within the file names surpassing the length limit and getting cutoff prematurely.

https://i.sstatic.net/KNgCv.png

I'm uncertain about the best approach to tackle this problem, so any assistance would be highly appreciated.

Answer №1

It is possible to display file names within a character limit while always showing the file extension by following this method:

def handle_file_name(file):
    MAX_CHARACTERS_ALLOWED = 20  # Adjust based on requirements
    file_name = file.name
    file_extension = file_name.split('.')[-1]
    file_name_without_extension = file_name[:-(len(file_extension) + 1)]

    truncated_name = file_name_without_extension
    if len(truncated_name) > MAX_CHARACTERS_ALLOWED:
        truncation_length = MAX_CHARACTERS_ALLOWED - 4 - len(file_extension)
        truncated_name = f"{truncated_name[:truncation_length]}....{file_extension}"

    return truncated_name

Explanation:

  • The handle_file_name function takes a file object as input and returns the modified filename.

  • The MAX_CHARACTERS_ALLOWED variable defines the maximum characters allowed for the displayed filename (excluding the file extension).

  • The full filename is stored in the file_name variable obtained from the file object's name property.

  • The file extension is extracted by splitting the file_name using the dot separator and selecting the last element as the extension.

  • The filename without the extension is obtained by removing the file extension from the full filename.

  • If the filename exceeds the maximum character limit, it is truncated to fit within the specified limit by replacing excess characters with an ellipsis (...) followed by the file extension.

  • The modified filename is then returned by the function.

Implementation in HTML:

<div class="file-name">
  <p>{{ handle_file_name(item) }}</p>
</div>

CSS Styling:

.file-name {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.file-name p {
  color: #333;
  margin: auto;
  font-size: 16px;
  padding: 8px;
  word-wrap: break-word;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nuxt - Auth module: Securely authenticating server-side requests

On a specific page, there is a requirement to load user-specific data using the fetch() hook. What is the process of accessing the authentication token on the server side in order to include it in this request? ...

The Vue.js modal is unable to resize below the width of its containing element

My challenge is to implement the Vue.js modal example in a larger size. I adjusted the "modal-container" class to be 500px wide, with 30px padding and a max-width of 80%. However, I'm facing an issue where the "modal-mask" class, containing the contai ...

Distinguishing Between CORS and JWT: Understand the Variances

After successfully developing and deploying a Django REST API on Heroku, I encountered an issue when trying to fetch the API in Vue CLI. I received a CORS error message, prompting some questions to arise: Should I enable CORS in the backend using a CORS ...

Is there a way to disable responsiveness on a website?

Currently, I am in the process of developing a responsive style sheet that is live on our website. However, it seems to display poorly on non-desktop devices due to being a work in progress. I am considering using JavaScript to enforce the desktop layout ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

Reduce the number of unnecessary HTTP requests for duplicate images in VueJS applications

Scenario: On a webpage, multiple components are provided with a list of users. Following this provision, a foreach loop is utilized to call an additional component for fetching the user's image. It is plausible that various components may contain the ...

Exploring how to utilize Jest with timers for vee validate integration

I am faced with a challenge in determining if my button is disabled as the disabled property keeps returning undefined. I have carefully reviewed and followed the guidelines provided at , but unfortunately, it does not seem to work as expected. I suspect t ...

Using dryscrape for web scraping: encountering an issue when selecting a radio button with CSS

I am attempting to extract data from a dynamically updated table on a webpage using dryscrape. The web page in question is located at . My code functions correctly with tables that are generated when the page is loaded initially. However, I now need to upd ...

Tips for incorporating `new google.maps.Marker()` with `vue2-google-maps` are as follows:1. First

Due to certain reasons, I find myself having to utilize new google.maps.Marker() with vue2-google-maps, but I'm unsure of where to begin as most documentation and tutorials use <GmapMarker ... /> in the HTML section instead. I've attempted ...

Determine the dynamic height of content in a TypeScript file

Could you please provide guidance on obtaining the height of the content within this particular div element? For example, I need to calculate the dynamic height of the content. https://i.sstatic.net/2kNk3.png code .html <div class="margin-top-4 ...

Two problems encountered with the scroll bar feature on a tabular display

Have 2 inquiries about the table displayed below: Question 1: The height of the table is set to 500px, but I am puzzled by the fact that it seems like the content below, which is not part of the table, appears within the table due to the scroll bar exten ...

Is there a way to eliminate the space between the content inside a table cell and its borders?

I am struggling with a table setup that includes three columns and multiple rows. The first column contains an image, causing the cells in that row to resize based on the image size. When text is added to the 2nd and 3rd columns, it automatically centers w ...

Toggle the accordion with just the icon and include a click event on the button

I'm looking to customize the accordion functionality by toggling it with icons only, while also adding a click event on the buttons themselves. I've attempted the following code snippet-- <html> <link href="https://cdn.jsdelivr.net ...

In the setup function, the composition API calculates the return value of the computed property before it is

I am currently working on editing a post using the state manager Vuex in Vue3 with Composition API. Below is the code I have implemented: <template> <div class="container py-5"> <h3 class="mb-5 border-top-0 border-start- ...

How to retrieve the index of a table row in Vue with Element UI?

Is there a way to add a button only to the first row of a table column (labeled as 'Option' in the example code) and check the row index using v-if="scope.row.index === 0"? The current method with scope.row.index is not working. <el- ...

Automatically generate nested object properties in VueJS for streamlining code structure

Understanding the Issue I have created a custom system to monitor specific "store" properties from a JSON in a NoSQL database. The structure is fairly straightforward, with nested objects that are necessary for various reasons. The data format resembles ...

How come my diary section (5th) is showing up/operating in my teacher's section (4th)?

My journey with HTML, CSS, and Javascript began as a beginner. After following a tutorial on YouTube and making some modifications, everything was running smoothly until the diary section unexpectedly appeared under the teacher's section, which should ...

CSS media query to target specific viewport width

In my JavaScript code, I am dynamically creating a meta viewport. I set the value of this viewport to be 980px using the following script: var customViewPort=document.createElement('meta'); customViewPort.id="viewport"; customViewPort.name = "vie ...

Enhancing Image Quality in JavaFx's Scene Builder

Hey everyone! I've been using JavaFx scene builder to create a user interface with some png images. Up to now, I've been using labels and enlarging them to display the pictures, but this solution isn't ideal because I need to create multipl ...

Ensure that the div is styled with a white background and positioned next to another div with a right margin

I have a white-colored div that needs to be positioned next to another element on a webpage. Additionally, I need a paragraph placed on top of this div for information purposes. Please refer to the following link to see what I am trying to achieve: https:/ ...