function to truncate string in javascript code example
Example 1: javascript cut string if too long
if (string.length > 25) {
string = string.substring(0, 24) + "...";
}
function truncate(str, n){
return (str.length > n) ? str.substr(0, n-1) + '…' : str;
};
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
short = long.replace(/(.{7})..+/, "$1…");
Example 2: javascript truncate string full word
const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;
truncate('This is a long message', 20, '...');