You can do this using various techniques. Some of them are as follows:
Method 1: Using Plain Javascript:
You can do it using the simple simple Javascript expression as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function trimString(str, maxLen) { if (str.length <= maxLen) { return str; } var trimmed = str.substr(0, maxLen); return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…'; } // Let's test it sentenceOne = "too short"; sentencetwo = "more than the max length"; console.log(trimString(sentenceOne, 15)); console.log(trimString(sentencetwo, 15)); |
Output:
1 2 3 4 |
too short more than the… |
Method two: Using trim() function of Jquery:
In order to trim a string, firstly you can use the $.trim()
function of Jquery to make the input string neat(removes all newlines, spaces and tabs from the beginning and end of the supplied string).
Since you would be using the $.trim()
function of Jquery, don’t forgot to include the library file of Jquery:
1 2 3 |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> |
And here is a simple solution to this task :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
var ellipsis = "..."; function TrimLength(text, maxLength) { text = $.trim(text); if (text.length > maxLength) { text = text.substring(0, maxLength - ellipsis.length) return text.substring(0, text.lastIndexOf(" ")) + ellipsis; } else { return text; } } // And let's test it sentence = "This is the example to trim a word. Using trim function of jquery."; for (var i = 10; i <= 50; i += 10){ console.log(TrimLength(sentence, i)); }; |
Output:
1 2 3 4 5 6 7 |
This... This is the... This is the example to... This is the example to trim a word.... This is the example to trim a word. Using trim... |
And if you want to truncate a string to nearest white space using javascript, you can refer this article :
Truncating string to nearest white space using Javascript .


Den Gutschein koennte ich gut gebrauchen, um eine neue Brille zu kaufen und den FIlm dann auch in scharf sehen zu koennen.
coupons http://zophim.me/user/savingplaza3/
It's spooky how clever some ppl are. Thnsak!