How to shorten a string by replacing some characters with an ellipsis

Viewed 360

I am using an <input type="file"> element for file upload, and getting the filename. I am now trying to display the file name, but reduce the total string length. To achieve that, I wanted to add an ellipsis at a specific index and display the rest of the characters.

Like for example: if the filename is abcxyz.exe, I want the filename to look like abc..z.exe.

Is there any way to display it in this way ?

I am using this method, but it adds an ellipsis to replace all characters from the position given as a parameter.

function truncate(str, n){
    return (str.length > n) ? str.substr(0, n-5) + '&hellip;' + str.substring(str.indexOf(".") + 1) : str;
};
1 Answers

If I understand correctly, n represents the maximum length of the string. If the string is longer, you want to replace a substring by the ellipsis character, such that the resulting string has a length of n. If possible, you also want that ellipsis to be placed before the extension of the filename, leaving one character visible before the final dot.

Some things to consider:

  • Use lastIndexOf instead of indexOf, as the last occurrence really determines where the file extension starts.
  • Don't use the substr method, as it is considered a legacy feature in ECMAScript. I prefer slice.
  • Make the necessary calculations so to ensure that after the insertion of the ellipsis you arrive at the correct length.
  • Deal with boundary cases, where the filename has no extension, or where the extension itself is longer than n.
  • Don't use the HTML entity &hellip;, as that will limit the use of this function to HTML output only. Instead put the actual … character, which will both work for HTML and plain text.

Here is the code I would suggest:

function truncate(str, n) {
    if (str.length <= n) return str; // Nothing to do
    if (n <= 1) return "…"; // Well... not much else we can return here!
    let dot = str.lastIndexOf("."); // Where the extension starts
    // How many characters from the end should remain:
    let after = dot < 0 ? 1 : Math.max(1, Math.min(n - 2, str.length - dot + 2));
    // How many characters from the start should remain:
    let before = n - after - 1; // Account for the ellipsis
    return str.slice(0, before) + "…" + str.slice(-after);
}
Related