Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Truncate A String In jQuery?

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?

like image 481
hd. Avatar asked Jan 09 '11 06:01

hd.


People also ask

How do you shorten a string in JavaScript?

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 &hellip; (…) to the clipped string. function truncate( str, n, useWordBoundary ){ if (str. length <= n) { return str; } const subString = str.


1 Answers

From: jQuery text truncation (read more style)

Try this:

var title = "This is your title";  var shortText = jQuery.trim(title).substring(0, 10)     .split(" ").slice(0, -1).join(" ") + "..."; 
  • Tested here

And you can also use a plugin:

  • jQuery Expander 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); 
like image 138
Naveed Avatar answered Oct 08 '22 08:10

Naveed