Created
January 19, 2012 02:37
-
-
Save mseeley/1637329 to your computer and use it in GitHub Desktop.
Truncating a string at word break
This file contains 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
/** | |
* 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'))); |
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
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!