Tengo títulos largos y quiero truncarlos pero de manera que no se rompan las palabras, quiero decir que el corte ocurre entre palabras y no corta una palabra.
¿Cómo puedo hacerlo usando jquery?
De: truncamiento de texto jQuery (leer más estilo)
Prueba esto:
var title = "This is your title"; var shortText = jQuery.trim(title).substring(0, 10) .split(" ").slice(0, -1).join(" ") + "...";Y también puedes usar un complemento:
Como una extensión de String
String.prototype.trimToLength = function(m) { return (this.length > m) ? jQuery.trim(this).substring(0, m).split(" ").slice(0, -1).join(" ") + "..." : this; };Usar como
"This is your title".trimToLength(10);La solución anterior no funcionará si la cadena original no tiene espacios.
Prueba esto:
var title = "This is your title"; var shortText = jQuery.trim(title).substring(0, 10) .trim(this) + "..."; function truncateString(str, length) { return str.length > length ? str.substring(0, length - 3) + '...' : str }