Skip to content

Instantly share code, notes, and snippets.

@stevoland
Created September 12, 2012 09:45
Show Gist options
  • Save stevoland/3705596 to your computer and use it in GitHub Desktop.
Save stevoland/3705596 to your computer and use it in GitHub Desktop.
Hyphenate long words
/**
* Add a soft hypen (­) to any words in the string longer than the given character length
*
* @param {string} str Input string
* @param {int} maxWordSize Max character length of a word
* @param {int} minFragmentSize [optional] Minimum chars to leave after a hyphen
* @return {string}
*/
var hyphenateLongWords = function (str, maxWordSize, minFragmentSize) {
// TODO: Find out char codes of word break chars
// TODO: Cope with html entities in input string
var l = str.length,
i,
j,
// Chars client will break at - including those forced by allowBreaks function above
wordBreaks = ['/', '\\', '.', '?', '!', ' ', '-', '(', '@'],
hyphenated = '',
wordSize,
fragmentSize,
smallestFragment,
fragmentDiff,
numHyphens;
if (!maxWordSize) {
return str;
}
if (minFragmentSize == null) {
minFragmentSize = Math.floor(maxWordSize/2);
}
// Loop through chars
for (i=0; i<l; i+=1) {
// Find next word ending
for (j=i; j<l; j+=1) {
if ($.inArray(str[j], wordBreaks) !== -1) {
break;
}
}
wordSize = j-i;
// If too long split into fragments seperated by &shy;
if (wordSize > maxWordSize) {
numHyphens = Math.floor(wordSize / maxWordSize);
fragmentSize = maxWordSize;
smallestFragment = wordSize % maxWordSize;
// If final fragment is too small reduce size of previous fragments to compensate
if (smallestFragment !== 0 && smallestFragment < minFragmentSize) {
fragmentDiff = minFragmentSize - smallestFragment;
fragmentSize -= Math.ceil(fragmentDiff / numHyphens);
}
while (i < j) {
if (numHyphens) {
hyphenated += str.substr(i, fragmentSize) + '&shy';
i += fragmentSize;
numHyphens -= 1;
} else {
hyphenated += str.substring(i, j+1);
i = j;
}
}
} else {
hyphenated += str.substring(i, j+1);
}
i = j;
}
return hyphenated;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment