How can we use Javascript to trim a string to length? or truncate a string and append 3 dots in javascript? Let’s do it today. Javascript provides us substring function which sometimes is a cause of confusion . So today let’s trim a string to a length in javascript by hiding complexity of the substring. we will write a prototype function for this activity for String class.
String.prototype.setStringLength = function (length) { if (this.length > length) return this.substring(0, length) + '...'; else return this; };
write the above function before using it! How to use it? simple!
string exampleString = "I am a huge string and please trim me!"; alert('trimmed string to 10 length '+ exampleString.setStringLength(10));
Let me remind you it will append 3 characters so if you specify 10 as length it will trim to 10 + add 3 dots = 13 characters!