javascript truncate string to length code example

Example 1: How to make string shorter javascript

const string = "Name".slice(0, 250).concat('...');
const string2 = "Name".substring(0, 250).concat('...');

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}`;

// Example
truncate('This is a long message', 20, '...');

Example 3: javascript truncate string

var string = "ABCDEFG";
var truncString = string.substring(0, 3); //Only keep the first 3 characters
console.log(truncString); //output: "ABC"

Tags:

Html Example