Created
January 18, 2017 22:45
-
-
Save mijimoco/6bb6a596d63ef83b543ecc57fbcce052 to your computer and use it in GitHub Desktop.
Truncate a string
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, num) { | |
// Clear out that junk in your trunk | |
var trunStr = ""; | |
if (str.length>num){ //first checking wheter given string needs to truncated | |
if (num>3) { // check whether given num is bigger than 3 or not | |
trunStr = str.slice(0, num-3); //we need to take additional 3 from the ... | |
console.log(trunStr); | |
return trunStr + "..."; | |
} else { // not bigger than 3, so we do not include three dots within our calculation | |
trunStr = str.slice(0, num); | |
console.log(trunStr); | |
return trunStr + "..."; | |
} | |
} else return str; //string does not need to be truncated so, we return it as it is | |
// return str; | |
} | |
truncateString("Absolutely Longer", 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment