Skip to content

Instantly share code, notes, and snippets.

@riddle
Created November 20, 2010 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riddle/708212 to your computer and use it in GitHub Desktop.
Save riddle/708212 to your computer and use it in GitHub Desktop.
Breaks long strings of text ever N character
var wrap_break = function(text, br) {
var delimit = 9, // break words every n characters
style = 2, // allow n extra characters (immediately before consequent space)
words = text.split(' '),
new_words = [];
br = br || '<wbr>';
for (var i = 0; i < words.length; i++) {
var word = words[i],
length = word.length,
times = Math.floor(length / delimit),
rest = length % delimit,
bits_array = [],
last_bit = '';
for (var j = 1; j < times + 1; j++) {
var start = (j - 1) * delimit;
var end = j * delimit;
var pass = word.substring(start, end);
if ((j == times) && (rest > 0)) {
if (rest <= style) {
pass += word.substring(end, length);
} else {
last_bit = word.substring(end, length);
}
}
bits_array.push(pass);
if (last_bit) {
bits_array.push(last_bit);
}
}
if (times === 0) {
new_words.push(word);
}
var new_word = bits_array.join(br);
new_words.push(new_word);
}
var new_text = new_words.join(' ');
return new_text;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment