I want to truncate a string after certain characters length in javascript. When the character length is reached then string should not be cut in the middle of the word rather it should complete the word and then truncate the string. What I have tried uptil now cuts the string before the cutting word. I want to include the cutting word in returned string. Here is my code:
function truncateString(yourString, maxLength) {
var trimmedString = yourString.substr(0, maxLength);
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
return trimmedString;
}
now when I call this function on with following parameters:
truncateString('The quick brown fox jumps over the lazy dog',6)
The output is 'The' rather than 'The quick
.
Please point out what I need to change. Thanks