1var string = "ABCDEFG";
2var truncString = string.substring(0, 3); //Only keep the first 3 characters
3console.log(truncString); //output: "ABC"
1const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`;
2
3// Example
4truncate('This is a long message', 20, '...');
1function truncateString(str, num) {
2 if (str.length > num) {
3 return str.slice(0, num) + "...";
4 } else {
5 return str;
6 }
7}
8
1function truncateString(str, num) {
2 if (num > str.length){
3 return str;
4 } else{
5 str = str.substring(0,num);
6 return str+"...";
7 }
8
9}
10
11res = truncateString("A-tisket a-tasket A green and yellow basket", 11);
12alert(res)
1var length = 3;
2var myString = "ABCDEFG";
3var myTruncatedString = myString.substring(0,length);
4// The value of myTruncatedString is "ABC"
5
1_.truncate('hi-diddly-ho there, neighborino');
2// => 'hi-diddly-ho there, neighbo...'
3
4_.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' '});
5// => 'hi-diddly-ho there,...'
6
7_.truncate('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/});
8// => 'hi-diddly-ho there...'
9
10_.truncate('hi-diddly-ho there, neighborino', { 'omission': ' [...]'});
11// => 'hi-diddly-ho there, neig [...]'