Limit the length of a text with JavScript (Jquery)

0

How can I limit a text string with javascript or jquery ???

I have a data brought from the database, but that data is too long and I unravel my design, what I want is for example, if that data is greater than a certain number of characters co javascript or jquery put ".. . "substituting the rest of the paragraph, how can I do that?

Thanks in advance :)

    
asked by Moisés Aguilar 16.05.2018 в 19:02
source

3 answers

2

You can do something like this:

var str = "Hello world!";
var res = str.substring(0, 2);
var final = res +"...";
console.log(final);
    
answered by 16.05.2018 / 19:33
source
1

Try this:

function recortar(){
   var logitud = 20;
   var dato = "texto largo";
   var datoAMostrar = "";

   for(var i = 0; i < logitud; i++)
       datoAMostrar = datoAMostrar + dato[i];

   datoAMostrar = datoAMostrar + "...";

}

You must be careful because if the length (number of characters to show) is greater than the text, an undefined will appear. This would be arranged in the following way:

function recortar(){
   var logitud = 20;
   var dato = "texto largo";
   var datoAMostrar = "";

   for(var i = 0; i < logitud && i < dato.length; i++)
       datoAMostrar = datoAMostrar + dato[i];

   datoAMostrar = datoAMostrar + "...";

}
    
answered by 16.05.2018 в 19:14
1

It is a solution similar to the previous ones, but maybe it is something shorter than the second, and more elaborate than the first one:

function recortaDatos(dato,longitud){
    var respuesta = dato;
    if(dato.length>longitud){
       respuesta = dato.substring(0,longitud-3)+"...";
    }
    return respuesta;
}

Now, at the time of collecting the data, within the loop that I suppose you will create to iterate between those data, simply always pass the same data through this filter: (example)

for(var i =0; i<listado.length; i++){
      for (var j = 0; j< listado[i].length; j++){
           $(donde rellenes el dato).text(recortaDatos(listado[i][j]));
      }
}

I hope it helps you.

    
answered by 18.05.2018 в 13:31