Link to home
Start Free TrialLog in
Avatar of CAS-IT
CAS-IT

asked on

JavaScript to cut a long string between words

Hi all,

I'm trying to figure out how to write a JavaScript function that will trim some text to a specific length, but not in the middle of a word - it could only trim on whitespace. So, if I called it like trimText(strTheText, 500), then it wouldn't necessarily trim at 500 - it might trim at 497 if there is a word between 498 and 506. We can assume that it always trims smaller than the given length. Even if there is a space at 501, which is closer to 500, it should still trim back at 493 or whatever.

This is what I started with, when I found it trimming in the middle of a word:

function trimText(strTheText, intSize) {
  if(strTheText.length <= intSize) {
    return strTheText;
  }
  else {
    return strTheText.substr(0,500) + '...';
  }
}


Anyone have any ideas on this? Code would be best ... thanks!



}
ASKER CERTIFIED SOLUTION
Avatar of Gregg
Gregg
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CAS-IT
CAS-IT

ASKER

Wow, 1 line!!

Shame I get an error.

TypeError: str.slice is not a function

Well, I ran through it, and using it the long way (without everything on 1 line) works.

Here's my final:

$("#myDiv .stuff").each(function(){
    var theString = String($(this).text());
    theString = theString.slice(0, 75);
    theString = theString.substr(0, theString.lastIndexOf(" "));
    $(this).text(theString + " ...");
});

Thanks!!
He CAS-IT, Thanks!

Im sorry about error. I will have take another look. I thought i had it right. Good to see you have it working. Good job converting to jquery!

Gregg