Last active
April 17, 2020 19:09
-
-
Save jhonsore/afaf567f1ab16e486e55e85bc9d6ff39 to your computer and use it in GitHub Desktop.
Truncate a string if it is longer than the specified number of characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function truncateString(str, len, append) | |
{ | |
var newLength; | |
append = append || ""; //Optional: append a string to str after truncating. Defaults to an empty string if no value is given | |
if (append.length > 0) | |
{ | |
append = " "+append; //Add a space to the beginning of the appended text | |
} | |
if (str.indexOf(' ')+append.length > len) | |
{ | |
return str; //if the first word + the appended text is too long, the function returns the original String | |
} | |
str.length+append.length > len ? newLength = len-append.length : newLength = str.length; // if the length of original string and the appended string is greater than the max length, we need to truncate, otherwise, use the original string | |
var tempString = str.substring(0, newLength); //cut the string at the new length | |
tempString = tempString.replace(/\s+\S*$/, ""); //find the last space that appears before the substringed text | |
if (append.length > 0) | |
{ | |
tempString = tempString + append; | |
} | |
return tempString; | |
}; | |
console.log(truncateString("Make sure an element and number of items to truncate is provided", 15,"...")); | |
//Got it on https://www.nfollmer.com/2016/07/06/truncate-string-word-break-javascript/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment