文字列を切り詰める


  • は、与えられた最大文字列長(第2引数)より長い場合、文字列(第1引数)を切り捨てます.短縮された文字列を返します.
  • function truncateString(str, num) {
      return str;
    }
    
    truncateString("A-tisket a-tasket A green and yellow basket", 8);
    
  • 最初にスライスの仕組みを見てみましょう.
  • // slice() method should work for this as well; whats slice?
    let name = "randy";
    console.log(name.slice(0, 3)); // will display ran
    
  • 回答:
  • function truncateString(str, num) {
      if (str.length > num) {
        return str.slice(0, num) + "...";
      }
      return str;
    }
    
    console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8)); // will display "A-tisket..."
    // console.log("A-tisket a-tasket A green and yellow basket".length); will display 43