Last active
April 30, 2021 13:17
-
-
Save supermarsx/89ffd9c2cd33d41dc138e35b8411f5be to your computer and use it in GitHub Desktop.
Truncate a given string with plain javascript
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
/* | |
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 + "…"; | |
return truncatedString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment