Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 299653
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T06:50:33+00:00 2026-05-12T06:50:33+00:00

Does anyone have a more sophisticated solution/library for truncating strings with JavaScript and putting

  • 0

Does anyone have a more sophisticated solution/library for truncating strings with JavaScript and putting an ellipsis on the end, than the obvious one:

if (string.length > 25) {
  string = string.substring(0, 24) + "...";
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T06:50:33+00:00Added an answer on May 12, 2026 at 6:50 am

    Essentially, you check the length of the given string. If it’s longer than a given length n, clip it to length n (substr or slice) and add html entity … (…) to the clipped string.

    Such a method looks like

    function truncate(str, n){
      return (str.length > n) ? str.slice(0, n-1) + '…' : str;
    };
    

    If by ‘more sophisticated’ you mean truncating at the last word boundary of a string then you need an extra check.
    First you clip the string to the desired length, next you clip the result of that to its last word boundary

    function truncate( str, n, useWordBoundary ){
      if (str.length <= n) { return str; }
      const subString = str.slice(0, n-1); // the original check
      return (useWordBoundary 
        ? subString.slice(0, subString.lastIndexOf(" ")) 
        : subString) + "&hellip;";
    };
    

    You can extend the native String prototype with your function. In that case the str parameter should be removed and str within the function should be replaced with this:

    String.prototype.truncate = String.prototype.truncate || 
    function ( n, useWordBoundary ){
      if (this.length <= n) { return this; }
      const subString = this.slice(0, n-1); // the original check
      return (useWordBoundary 
        ? subString.slice(0, subString.lastIndexOf(" ")) 
        : subString) + "&hellip;";
    };
    

    More dogmatic developers may chide you strongly for that ("Don’t modify objects you don’t own". I wouldn’t mind though). [edit 2023] A method to extend the String without tampering with its prototype may be to use a Proxy. See this stackblitz snippet.

    An approach without extending the String prototype is to create
    your own helper object, containing the (long) string you provide
    and the beforementioned method to truncate it. That’s what the snippet
    below does.

    const LongstringHelper = str => {
      const sliceBoundary = str => str.substr(0, str.lastIndexOf(" "));
      const truncate = (n, useWordBoundary) => 
            str.length <= n ? str : `${ useWordBoundary 
              ? sliceBoundary(str.slice(0, n - 1))
              : str.slice(0, n - 1)}&hellip;`;
      return { full: str,  truncate };
    }; 
    const longStr = LongstringHelper(`Lorem ipsum dolor sit amet, consectetur 
    adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore 
    magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation 
    ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
    irure dolor in reprehenderit in voluptate velit esse cillum dolore 
    eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum`);
    
    const plain = document.querySelector("#resultTruncatedPlain");
    const lastWord = document.querySelector("#resultTruncatedBoundary");
    plain.innerHTML = 
      longStr.truncate(+plain.dataset.truncateat, !!+plain.dataset.onword);
    lastWord.innerHTML = 
      longStr.truncate(+lastWord.dataset.truncateat, !!+lastWord.dataset.onword);
    document.querySelector("#resultFull").innerHTML = longStr.full;
    body {
      font: normal 12px/15px verdana, arial;
    }
    
    p {
      width: 450px;
    }
    
    #resultTruncatedPlain:before {
      content: 'Truncated (plain) n='attr(data-truncateat)': ';
      color: green;
    }
    
    #resultTruncatedBoundary:before {
      content: 'Truncated (last whole word) n='attr(data-truncateat)': ';
      color: green;
    }
    
    #resultFull:before {
      content: 'Full: ';
      color: green;
    }
    <p id="resultTruncatedPlain" data-truncateat="120" data-onword="0"></p>
    <p id="resultTruncatedBoundary" data-truncateat="120" data-onword="1"></p>
    <p id="resultFull"></p>

    Finally, you can use css only to truncate long strings in HTML nodes. It gives you less control, but may well be viable solution.

    body {
      font: normal 12px/15px verdana, arial;
      margin: 2rem;
    }
    
    .truncate {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 30vw;
    }
    
    .truncate:before{
      content: attr(data-longstring);
    }
    
    .truncate:hover::before {
      content: attr(data-longstring);
      width: auto;
      height: auto;
      overflow: initial;
      text-overflow: initial;
      white-space: initial;
      background-color: white;
      display: inline-block;
    }
    <div class="truncate" data-longstring="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."></div>
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 222k
  • Answers 222k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer About the "POP 3 connection strings" part, maybe this RFC… May 13, 2026 at 12:17 am
  • Editorial Team
    Editorial Team added an answer Are you waiting to bind the event until the Dom… May 13, 2026 at 12:17 am
  • Editorial Team
    Editorial Team added an answer Access has a built-in macro language called Visual Basic for… May 13, 2026 at 12:17 am

Related Questions

I've found a solution, see my own answer below. Does anyone have a more
Does anyone have a good technique (or tutorial) to implement rulers within a C#
I have a byte array generated by a random number generator. I want to
I have been working on a scheduling website for the past few weeks. I

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.