code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

07 Truncate String

/**
 * Created by Ashish Patel
 * Copyright © 2017 ashish.me
 * ashishsushilpatel@gmail.com 
 */

/**
 * Program:
 * Truncate a string (first argument) if it is longer than the given maximum string length (second argument). 
 * Return the truncated string with a ... ending.
 * Note that inserting the three dots to the end will add to the string length.
 * However, if the given maximum string length num is less than or equal to 3, then the addition of the three dots does not add to the string length in determining the truncated string.
 */

function truncateString(str, num) {
    if(str.length > num){
        return `${str.slice(0, num > 3 ? num-3 : num )  }...`;
    }
    return str;
}
  
console.log(truncateString("A-tisket a-tasket A green and yellow basket", 11));

Created 2019-11-24T04:41:20+05:18 · Edit