web-dev-qa-db-fra.com

Je souhaite tronquer un texte ou une ligne avec des points de suspension à l'aide de JavaScript

Je cherche un script simple qui peut tronquer une chaîne avec des points de suspension (...)

Je veux tronquer quelque chose comme 'this is a very long string' à 'this is a ve...'

Je ne veux pas utiliser CSS ou PHP.

48
Dollar Friend
function truncate(input) {
   if (input.length > 5)
      return input.substring(0,5) + '...';
   else
      return input;
};

ou un nouveau style terser JS ...

const truncate = (input) => input.length > 5 ? `${input.substring(0, 5)}...` : input;
82
El Ronnoco

KooiInc a une bonne réponse à cela. Pour résumer:

String.prototype.trunc = 
      function(n){
          return this.substr(0,n-1)+(this.length>n?'…':'');
      };

Vous pouvez maintenant:

var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not...

Et si vous le préférez en tant que fonction, selon le commentaire de @ AlienLifeForm:

function truncateWithEllipses(text, max) 
{
    return text.substr(0,max-1)+(text.length>max?'…':''); 
}

Le crédit complet revient à KooiInc pour cela.

34
Jarrod

Quelque chose comme:

var line = "foo bar lol";
line.substring(0, 5) + '...' // gives "foo b..."
5
user180100

Pour empêcher les points au milieu d'un mot ou après un symbole de ponctuation.

let parseText = function(text, limit){
  if (text.length > limit){
      for (let i = limit; i > 0; i--){
          if(text.charAt(i) === ' ' && (text.charAt(i-1) != ','||text.charAt(i-1) != '.'||text.charAt(i-1) != ';')) {
              return text.substring(0, i) + '...';
          }
      }
       return text.substring(0, limit) + '...';
  }
  else
      return text;
};
    
    
console.log(parseText("1234567 890",5))  // >> 12345...
console.log(parseText("1234567 890",8))  // >> 1234567...
console.log(parseText("1234567 890",15)) // >> 1234567 890
5
davidivad

Manière la plus simple et flexible: JSnippet DEMO

Style de fonction:

function truncString(str, max, add){
   add = add || '...';
   return (typeof str === 'string' && str.length > max ? str.substring(0,max)+add : str);
};

Prototype:

String.prototype.truncString = function(max, add){
   add = add || '...';
   return (this.length > max ? this.substring(0,max)+add : this);
};

Usage:

str = "testing with some string see console output";

//By prototype:
console.log(  str.truncString(15,'...')  );

//By function call:
console.log(  truncString(str,15,'...')  );
4
Shlomi Hassid

Cela le limitera au nombre de lignes auquel vous le souhaitez et sera réactif

Une idée que personne n'a suggérée, en la faisant en fonction de la hauteur de l'élément et en la retirant de là.

Violon - https://jsfiddle.net/hutber/u5mtLznf/ <- version ES6

Mais fondamentalement, vous voulez saisir la hauteur de ligne de l'élément, parcourir tout le texte et vous arrêter lorsqu'il est à une certaine hauteur de ligne:

'use strict';

var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;

var getLineHeight = function getLineHeight(element) {
  var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
  if (lineHeight === 'normal') {
    // sucky chrome
    return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
  } else {
    return parseFloat(lineHeight);
  }
};

linesElement.addEventListener('change', function () {
  truncateElement.innerHTML = truncateText;
  var truncateTextParts = truncateText.split(' ');
  var lineHeight = getLineHeight(truncateElement);
  var lines = parseInt(linesElement.value);

  while (lines * lineHeight < truncateElement.clientHeight) {
    console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
    truncateTextParts.pop();
    truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
  }
});

[~ # ~] css [~ # ~]

#truncateme {
   width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}
4
Jamie Hutber

Cela mettra les points de suspension au centre de la ligne:

function truncate( str, max, sep ) {

    // Default to 10 characters
    max = max || 10;

    var len = str.length;
    if(len > max){

        // Default to elipsis
        sep = sep || "...";

        var seplen = sep.length;

        // If seperator is larger than character limit,
        // well then we don't want to just show the seperator,
        // so just show right hand side of the string.
        if(seplen > max) {
            return str.substr(len - max);
        }

        // Half the difference between max and string length.
        // Multiply negative because small minus big.
        // Must account for length of separator too.
        var n = -0.5 * (max - len - seplen);

        // This gives us the centerline.
        var center = len/2;

        var front = str.substr(0, center - n);
        var back = str.substr(len - center + n); // without second arg, will automatically go to end of line.

        return front + sep + back;

    }

    return str;
}

console.log( truncate("123456789abcde") ); // 123...bcde (using built-in defaults) 
console.log( truncate("123456789abcde", 8) ); // 12...cde (max of 8 characters) 
console.log( truncate("123456789abcde", 12, "_") ); // 12345_9abcde (customize the separator) 

Par exemple:

1234567890 --> 1234...8910

Et:

A really long string --> A real...string

Pas parfait, mais fonctionnel. Pardonnez les commentaires excessifs ... pour les noobs.

3
bob
function truncate(string, length, delimiter) {
   delimiter = delimiter || "&hellip;";
   return string.length > length ? string.substr(0, length) + delimiter : string;
};

var long = "Very long text here and here",
    short = "Short";

truncate(long, 10); // -> "Very long ..."
truncate(long, 10, ">>"); // -> "Very long >>"
truncate(short, 10); // -> "Short"
2
polarblau

HTML avec JavaScript:

<p id="myid">My long long looooong text cut cut cut cut cut</p>

<script type="text/javascript">
var myid=document.getElementById('myid');
myid.innerHTML=myid.innerHTML.substring(0,10)+'...';
</script>

Le résultat sera:

My long lo...

À votre santé

G.

1
Gregory Machon

Si vous souhaitez couper une chaîne pour une longueur spécifiée et ajouter des points, utilisez

// Length to cut
var lengthToCut = 20;

// Sample text
var text = "The quick brown fox jumps over the lazy dog";

// We are getting 50 letters (0-50) from sample text
var cutted = text.substr(0, lengthToCut );
document.write(cutted+"...");

Ou si vous voulez couper non pas par la longueur mais avec le nombre de mots, utilisez:

// Number of words to cut
var wordsToCut = 3;

// Sample text
var text = "The quick brown fox jumps over the lazy dog";

// We are splitting sample text in array of words
var wordsArray = text.split(" ");

// This will keep our generated text
var cutted = "";
for(i = 0; i < wordsToCut; i++)
 cutted += wordsArray[i] + " "; // Add to cutted Word with space

document.write(cutted+"...");

Bonne chance...

1
Robik

Essaye ça

function shorten(text, maxLength, delimiter, overflow) {
  delimiter = delimiter || "&hellip;";
  overflow = overflow || false;
  var ret = text;
  if (ret.length > maxLength) {
    var breakpoint = overflow ? maxLength + ret.substr(maxLength).indexOf(" ") : ret.substr(0, maxLength).lastIndexOf(" ");
    ret = ret.substr(0, breakpoint) + delimiter;
  }
  return ret;
}

$(document).ready(function() {
  var $editedText = $("#edited_text");
  var text = $editedText.text();
  $editedText.text(shorten(text, 33, "...", false));
});

Commander un échantillon de travail sur Codepen http://codepen.io/Izaias/pen/QbBwwE

1
Izaias