Answers for "Truncate a string"

4

javascript truncate string

var string = "ABCDEFG";
var truncString = string.substring(0, 3); //Only keep the first 3 characters
console.log(truncString); //output: "ABC"
Posted by: Guest on May-20-2020
0

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);
Posted by: Guest on February-26-2021
0

Truncate a string

function truncateString(str, num) {
  // Clear out that junk in your trunk
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}
Posted by: Guest on June-24-2021
0

string truncate

text_truncate = function(str, length, ending) {
    if (length == null) {
      length = 100;
    }
    if (ending == null) {
      ending = '...';
    }
    if (str.length > length) {
      return str.substring(0, length - ending.length) + ending;
    } else {
      return str;
    }
  };
console.log(text_truncate('We are doing JS string exercises.'))
console.log(text_truncate('We are doing JS string exercises.',19))
console.log(text_truncate('We are doing JS string exercises.',15,'!!'))
Posted by: Guest on August-26-2021
-1

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...
Posted by: Guest on August-04-2020

Browse Popular Code Answers by Language