Skip to content

Instantly share code, notes, and snippets.

@juanbrusco
Created August 30, 2018 19:02
Show Gist options
  • Save juanbrusco/d2779bc62c49dd67f1f249e21f93d3ad to your computer and use it in GitHub Desktop.
Save juanbrusco/d2779bc62c49dd67f1f249e21f93d3ad to your computer and use it in GitHub Desktop.
Truncate a string - Javascript
truncate (str, length, ending) {
if (length == null) {
length = 100;
}
if (ending == null) {
ending = '...';
}
if (str.length > length) {
return str.substring(0, length - ending.length) + ending;
} else {
return str;
}
};
console.log(truncate('JS string exercises.'))
console.log(truncate('JS string exercises.',19))
console.log(truncate('S string exercises.',15,'...'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment