Dan Barzilay
Dan Barzilay

Reputation: 4983

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

Upvotes: 14

Views: 18420

Answers (7)

Azizi
Azizi

Reputation: 1

		
    var texte = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu magna at justo bibendum accumsan. Aliquam quam metus, hendrerit eget commodo at, sagittis eu lectus. Nunc quis purus urna. Etiam sollicitudin aliquam dui, vel rutrum ligula tincidunt id. In elementum ultricies ex ut bibendum. Proin ac purus id lorem pharetra commodo. Curabitur euismod commodo eleifend. Proin porttitor aliquet massa eu dapibus. Phasellus vitae tempor nibh. Donec venenatis ligula dui, at eleifend urna facilisis sed. Proin sollicitudin vehicula mi aliquam interdum. Quisque in erat purus. Ut ut ipsum nec odio mollis maximus. Vivamus nec ultricies mi, ut posuere augue.`;
    
    function cut(n,text) {
        if(n<text.length){
          while(text[n] != " " && n>0){
            n--;
          }
          return text.substr(0,n);
        }else{
          return text;
        }

		}
    
    document.getElementById("result").innerHTML = cut(5,texte);
<p id="result"></p>

Upvotes: 0

jDelforge
jDelforge

Reputation: 126

This simple function will work in any situation, plus adding 3 dots if needed :

function shortenString(source_string, max_length) {
    var short = source_string.substr(0, max_length);
    if (/^\S/.test(source_string.substr(max_length)))
        return short.replace(/\s+\S*$/, "") + '...';
    return short;
};

Example:

var title = "This function will work in any situation";
var short = shortenString(title, 30);

Upvotes: 0

kennebec
kennebec

Reputation: 104780

The lastIndexOf method can find the last space character in a string,

and passing a second argument sets an upper limit.

var cutat= string.lastIndexOf(' ',505);
if(cutat!=-1)string=string.substring(0,cutat)+'...';
//else the string is shorter than 505 (or has no spaces...)

Upvotes: 7

Bergi
Bergi

Reputation: 664548

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));

Upvotes: 19

T.J. Crowder
T.J. Crowder

Reputation: 1074365

It's a combination of a for loop, charAt, and a means of testing the character against ones you consider to be word delimiters. I'll use a regular expression for that:

function splitString(str, index) {
  var delim = /\s|[,\.]/; // Put any other character you consider
                          // a non-word char in the brackets.
                          // The initial \s is any whitespace, so
                          // space, tab, newline, etc.
  var ch;
  var i;

  // Loop until we find a matching delimiter or we run out of string    
  for (i = index;
       i >= 0 && !delim.test(str.charAt(i));
       --i) {
    // No body
  }
  if (i < 0) {
    // No break before, split word in middle
    return index;
  }
  return i + 1;
}

Live example | source

Upvotes: 2

Gavriel
Gavriel

Reputation: 19237

function cutAt(text, n) {
    if(text.length > n){
        for (; " .,".indexOf(text[n]) !== 0; n--){
        }
        return text.substr(0, n) + '...';
    }
    return text;
}
$('#desc').text(cutAt($('#desc').text(), 505));

Upvotes: -1

epoch
epoch

Reputation: 16605

You may want to have a look at Cutter.js

Cutter.js is a library used for truncating HTML code to limit its length, by word number, without losing the markup.

Upvotes: 1

Related Questions