Skip to content

Instantly share code, notes, and snippets.

@andershaig
Created March 14, 2014 16:44
Show Gist options
  • Save andershaig/9551562 to your computer and use it in GitHub Desktop.
Save andershaig/9551562 to your computer and use it in GitHub Desktop.
Truncating based on a maximum length looking for the last period
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<output id="op">Smart Truncate:<br></output>
</body>
</html>
var stringOne = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam aliquam tristique erat at imperdiet. Vivamus gravida ut diam vel sagittis. Maecenas facilisis porttitor nunc vel consectetur. Vestibulum tempus mi augue, scelerisque eleifend mauris rutrum vitae. Vivamus consectetur augue augue, eu euismod magna porttitor non. Donec blandit tempor vehicula. Integer pellentesque, nibh vitae interdum cursus, est leo commodo risus, et fermentum ante mauris a orci.";
var stringTwo = "Eliminate something superfluous from your life. Break a habit. Do something that makes you feel insecure. Carry out an action with complete attention and intensity as if it were your last First we will be best, and then we will be first. You do not have to be a fantastic hero to do certain things, to compete. You can be just an ordinary chap, sufficiently motivated to reach challenging goals. Men who try to do something and fail are infinitely better off than those who try to do nothing and succeed. I do not seek. I find.";
var stringThree = "Some people have greatness thrust upon them. Very few have excellence thrust upon them. Make the most of today. Translate your good intentions into actual deeds. Everything comes to him who hustles while he waits. Self-image sets the boundaries of individual accomplishment. Do or do not. There is no try. Every man takes the limits of his own field of vision, for the limits of the world. Begin difficult things while they are easy. A thousand-mile journey begins with one step. You cannot cross the sea merely by standing and staring at the water. Do not let yourself indulge in vain wishes.";
var smartTruncate = function (str, len) {
var splitAt = str.lastIndexOf('.', len);
return str.substring(0, splitAt + 1);
}
var op = document.getElementById('op');
op.innerHTML += '<hr>' + smartTruncate(stringOne, 64);
op.innerHTML += '<hr>' + smartTruncate(stringTwo, 64);
op.innerHTML += '<hr>' + smartTruncate(stringThree, 64);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment