Skip to content

Instantly share code, notes, and snippets.

@supermarsx
Last active April 30, 2021 13:17
Show Gist options
  • Save supermarsx/89ffd9c2cd33d41dc138e35b8411f5be to your computer and use it in GitHub Desktop.
Save supermarsx/89ffd9c2cd33d41dc138e35b8411f5be to your computer and use it in GitHub Desktop.
Truncate a given string with plain javascript
/*
truncateString
Truncate a given string
.parameters
string (string) - String to truncate
charNum (integer) - Number of chars to truncate for
useWordBoundary (boolean) - Use word boundaries, default: false
.returns
truncatedString (string) - Truncated string, original string if is below char count
*/
function truncate(string, charNum, useWordBoundary = false) {
if (string.length <= charNum) return string;
const filtratedString = string.substr(0, n - 1);
var truncatedString = useWordBoundary ?
filtratedString.substr(0, filtratedString.lastIndexOf(" ")) :
filtratedString + "&hellip;";
return truncatedString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment