Codiguillos de JavierB

Cortar texto por palabras

Supongamos que tenemos un texto: "Con diez cañones por banda, viento en popa, a toda vela, no corta el mar, sino vuela, un velero bergantín." y lo queremos cortar en trozos de 20 caracteres. Sería muy fácil, utilizando la función substr(), pero nos quedaría así:

Con diez cañones por
banda, viento en po
pa, a toda vela, no 
corta el mar, sino v
uela un velero berga
ntín.

Bastante chapuza ¿no? Tendremos que utilizar un poco más de código para que quede presentable:

Probar código

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Dividir frase</title>
<script type="text/javascript">
<!--
function dividir(txt) {
  numLetras = document.forms[0]['num'].value;
  palabras = txt.split(' ');
  cad = '';
  i=0;
  while (i < palabras.length) {
    tot=0;
   if (palabras[i].length >= numLetras) {
      cad += ' '+palabras[i]+'<br />';
      i++
    }
    else while (true) {
      if (tot + palabras[i].length + ((tot>0) ? 1 : 0) <= numLetras) {
        cad += ' '+palabras[i];
        tot += palabras[i].length + ((tot>0) ? 1 : 0);
        i++; 
        if (i > palabras.length-1) break;
      } 
      else {
        cad+='<br />';
        break;
      }
    } // end else while
  } // end while
  document.getElementById('cortado').innerHTML = cad;
} // end funcion
-->
</script>
</head>
<body>
<form action="">
<p>
Nº de letras: <input type="text" id="num" value="20" /><br />
<textarea id="texto" rows="5" cols="30"></textarea>
<input type="button" value="Dividir" onclick="dividir(texto.value)" /><br />
</p>
</form>
<div id="cortado"></div>
</body>
</html>

Subir Subir

 
  • Validar XHTML 1.0
  • Validar Css