Skip to content

Instantly share code, notes, and snippets.

@mijimoco
Created January 18, 2017 22:45
Show Gist options
  • Save mijimoco/6bb6a596d63ef83b543ecc57fbcce052 to your computer and use it in GitHub Desktop.
Save mijimoco/6bb6a596d63ef83b543ecc57fbcce052 to your computer and use it in GitHub Desktop.
Truncate a string
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