0
Q:

cut text if too long javascript

if(snippet.length > 1024) {
text = snippet.substring(0, 1024)//cuts to 1024
last = text.lastIndexOf(" ")//gets last space (to avoid cutting the middle of a word)
text = text.substring(0, last)//cuts from last space (to avoid cutting the middle of a word)
text = text + ` (...)`//adds (...) at the end to show that it's cut
}
1
if (string.length > 25) {
  string = string.substring(0, 24) + "...";
}

//or 

function truncate(str, n){
  return (str.length > n) ? str.substr(0, n-1) + '…' : str;
};

//or with CSS

p {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

//or with replace

short = long.replace(/(.{7})..+/, "$1…");
0

New to Communities?

Join the community