How Can I Truncate A String In jQuery?

JavascriptJqueryString

Javascript Problem Overview


I have long titles and want truncate them but in a way that no words break, I mean the cutting happen between words not cutting a word.

How can I do it using jquery?

Javascript Solutions


Solution 1 - Javascript

From: https://stackoverflow.com/questions/2248742/jquery-text-truncation-read-more-style/2249591#2249591

Try this:

var title = "This is your title";

var shortText = jQuery.trim(title).substring(0, 10)
    .split(" ").slice(0, -1).join(" ") + "...";

And you can also use a plugin:

As a extension of String

String.prototype.trimToLength = function(m) {
  return (this.length > m) 
    ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..."
    : this;
};

Use as

"This is your title".trimToLength(10);

Solution 2 - Javascript

The solution above won't work if the original string has no spaces.

Try this:

var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
                          .trim(this) + "...";

Solution 3 - Javascript

  function truncateString(str, length) {
     return str.length > length ? str.substring(0, length - 3) + '...' : str
  }

Solution 4 - Javascript

Instead of using jQuery, use css property text-overflow:ellipsis. It will automatically truncate the string.

.truncated { display:inline-block; 
             max-width:100px; 
             overflow:hidden; 
             text-overflow:ellipsis; 
             white-space:nowrap; 
           }

Solution 5 - Javascript

with prototype and without space :

 String.prototype.trimToLength = function (trimLenght) {
    return this.length > trimLenght ? this.substring(0, trimLenght - 3) + '...' : this
};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionhd.View Question on Stackoverflow
Solution 1 - JavascriptNaveedView Answer on Stackoverflow
Solution 2 - JavascriptVladimir KrivchenkoView Answer on Stackoverflow
Solution 3 - JavascriptKeatingView Answer on Stackoverflow
Solution 4 - JavascriptRamiz RajaView Answer on Stackoverflow
Solution 5 - JavascriptAmine BarigoView Answer on Stackoverflow