how to truncate in a string code example

Example 1: Truncate a String

const truncateString = (str, num) => {
  
  /*******  Method One(1)  *******/
      // Return the actual string if num is equal or greater than str, 
      // else return the slice/copy the str from index 0 to index n(num), then truncate. 
    return num >= str.length ? str : str.slice(0, num)+'...'
    
  /******* Method Two(2) *******/
    let newString = ''
    	// Return same string if number length is greater or equal
    if(num >= str.length) newString += str; 
    	// Split each string, set new string to the spliced arr, join the new string and truncate
    else newString += str.split('').splice(0, num).join('')+'...'

    return newString
  
  /******* Method Three(3) *******/
  let truncateString = ''
  	// Optimize, to aviod looping through str when it is greater than the num
  if(num >= str.length) {
    truncateString = str
    return truncateString
    }
  else for(let i = 0; i < num; i++) truncateString += str[i]
  return truncateString+'...'
  	
  	// OR
  
  let truncateString = ''
  for(let i = 0; i < num; i++) truncateString += str[i]
  	// Conditionally search to avoid result returning undefined for num greater than str length
  return num >= str.length ? str : truncateString+'...'
  
}
truncateString("Peter Piper picked a peck of pickled peppers", 11);

Example 2: Truncate a string

function truncateString(str, num) {
 
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}

truncateString("Lorem Ipsum placeholder text in any number of characters, words sentences or paragraphs", 9)  // returns Lorem Ips...

Tags:

Misc Example