JavaScript Smart Truncate String Wihout Breaking Words

Oct 30, 2019

Function

function truncate(str, n, suffix = '..') {  if (str.length <= n) return str  const subString = str.substr(0, n-1)  return subString.substr(0, subString.lastIndexOf(' ')) + suffix}

Usage

const str = truncate("I live in Malaysia", 11)  // "I live in.."

Protytype

String.prototype.truncate =  function( n, suffix = '...' ) {    if (this.length <= n) { return this; }    var subString = this.substr(0, n-1);    return subString.substr(0, subString.lastIndexOf(' ')) + suffix;  }

Usage

const str = "I live in Malaysia".truncate(11)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.