Skip to content

Instantly share code, notes, and snippets.

@mseeley
Created January 19, 2012 02:37
Show Gist options
  • Save mseeley/1637329 to your computer and use it in GitHub Desktop.
Save mseeley/1637329 to your computer and use it in GitHub Desktop.
Truncating a string at word break
/**
* Assumptions:
* Text is a UTF8 string
* Text is without HTML entities and HTML tags
* Suffix is added at nearest word break, excluding punctuation
* Length of the text string is longer than the suffix
* Arguments are assumed present and of correct type
*/
(function (exports) {
// \s: Whitespace
// \u0021-\u002F: ! " # $ % & ' ( ) * + , - . /
// \u003A-\u0040: : ; < = ? @
// \u005B-\u0060: [ \ ] ^ _ '
// \u007B-\u007F: { | } ~
// \u00A0-\u00BF: Inverted punctuations, fractions, glyphs, etc
// \b boundary not safe: http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode
// unicode ranges: http://www.utf8-chartable.de/unicode-utf8-table.pl?view=3
var lastword = /\w+$/,
blacklist = /[\s\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007F\u00A0-\u00BF]$/,
hellip = '\u2026',
empty = '';
exports.truncate = function (text, length, suffix) {
suffix = suffix || hellip;
text = text.slice(0, length - suffix.length).replace(lastword, empty);
while (text && blacklist.test(text)) {
text = text.replace(blacklist, empty);
}
return text ? text + suffix : empty;
};
}(this));
var s = 'Hello ! " # $ % & \' ( ) * + , - . / : ; < = ? @ [ \ ] ^ _ { | } ~ world';
// Truncate mid-way through last word
console.log(this.truncate(s, s.indexOf('r')));
@mseeley
Copy link
Author

mseeley commented Jan 19, 2012

Note to self, \w is also ASCII-only; same flaw as \b

@centricle
Copy link

You people & your fake ellipses ;-)

If you're assuming UTF8, why not go with … (\u2026)?

Thinks of all the trees you'll save by omitting those two extra characters!

@mseeley
Copy link
Author

mseeley commented Jan 23, 2012

Logical change to me. Unicode or bust.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment