Shorten a string with ellipsis

PHOTO EMBED

Tue Aug 09 2022 19:28:41 GMT+0000 (Coordinated Universal Time)

Saved by @johnnye562 #javascript

const shorten = (text, length = 10, ellipsisCount = 3) => {
  if (!(typeof text === "string" || text instanceof String)) {
    console.error(`expecting a string, ${typeof text} provided`)
    return ""
  }
  if (isNaN(length) || isNaN(ellipsisCount)) {
    console.error("length and ellipsisCount must be valid numbers")
    return
  }
  
  if (text.length <= length) {
    return text
  }
  const ellipsis = Array.from(Array(ellipsisCount)).map(() => ".").join("")
  return `${text.substr(0, length)}${ellipsis}`
}

shorten("I am some text", 4, 2) // I am..
content_copyCOPY

https://justacoding.blog/9-useful-javascript-utility-functions/