1var string = "ABCDEFG";
2var truncString = string.substring(0, 3); //Only keep the first 3 characters
3console.log(truncString); //output: "ABC"
1const truncateString = (str, num) => {
2
3 /******* Method One(1) *******/
4 // Return the actual string if num is equal or greater than str,
5 // else return the slice/copy the str from index 0 to index n(num), then truncate.
6 return num >= str.length ? str : str.slice(0, num)+'...'
7
8 /******* Method Two(2) *******/
9 let newString = ''
10 // Return same string if number length is greater or equal
11 if(num >= str.length) newString += str;
12 // Split each string, set new string to the spliced arr, join the new string and truncate
13 else newString += str.split('').splice(0, num).join('')+'...'
14
15 return newString
16
17 /******* Method Three(3) *******/
18 let truncateString = ''
19 // Optimize, to aviod looping through str when it is greater than the num
20 if(num >= str.length) {
21 truncateString = str
22 return truncateString
23 }
24 else for(let i = 0; i < num; i++) truncateString += str[i]
25 return truncateString+'...'
26
27 // OR
28
29 let truncateString = ''
30 for(let i = 0; i < num; i++) truncateString += str[i]
31 // Conditionally search to avoid result returning undefined for num greater than str length
32 return num >= str.length ? str : truncateString+'...'
33
34}
35truncateString("Peter Piper picked a peck of pickled peppers", 11);
1function truncateString(str, num) {
2 // Clear out that junk in your trunk
3 if (str.length > num) {
4 return str.slice(0, num) + "...";
5 } else {
6 return str;
7 }
8}
9
1function truncateString(str, num) {
2
3 if (str.length > num) {
4 return str.slice(0, num) + "...";
5 } else {
6 return str;
7 }
8}
9
10truncateString("Lorem Ipsum placeholder text in any number of characters, words sentences or paragraphs", 9) // returns Lorem Ips...
11