Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut a string after n characters, but if it's in the middle of a word cut the whole word

I'm trying to make a JS function that cuts a string after n characters - that works. The problem is if it's in the middle of a word it looks bad, so I need your help making it cut the whole word if it's the middle of it.

My code so far:

if($('#desc').text().length > 505){
  str = $("#desc").text();
  $('#desc').text(str.substring(0, 505)).append('...');
}

P.S

  • #desc is the div that contains my string.
  • you can use jQuery.
like image 469
Dan Barzilay Avatar asked May 25 '12 08:05

Dan Barzilay


People also ask

How do you trim a word in JavaScript?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How do you cut the last word of a string?

To remove the last word from a string, get the index of the last space in the string, using the lastIndexOf() method. Then use the substring() method to get a portion of the string with the last word removed. Copied!

How do you find the length of a string in JavaScript?

The length of a string in JavaScript can be found using the . length property. Since . length is a property it must be called through an instance of a string class.


1 Answers

function cut(n) {
    return function textCutter(i, text) {
        var short = text.substr(0, n);
        if (/^\S/.test(text.substr(n)))
            return short.replace(/\s+\S*$/, "");
        return short;
    };
}
$('#desc').text(cut(505));
like image 53
Bergi Avatar answered Sep 20 '22 18:09

Bergi