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)