Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created May 18, 2010 04:08
Show Gist options
  • Save TooTallNate/404593 to your computer and use it in GitHub Desktop.
Save TooTallNate/404593 to your computer and use it in GitHub Desktop.
A quick and dirty function that breaks apart a (long) String based on full words and a maximum line width (in characters).
// Adds a 'fitTextToWidth' function. Which essentially accepts a String and
// an Number (int) parameters. The String is a long string of text (i.e.
// dialoge in a RPG) and adds '\n' characters throughout the String.
//
// The placement of '\n' characters is determined by the second param, which
// should be the maximum width of a single line of text.
//
// Depends on Prototype's Language extensions ($w, Enumberable, etc.). Meant
// to be used with my Simple Game Framework.
function fitTextToWidth(str, width) {
return $w(str).inject([], function(rtn, val, index) {
var curSize = val.length;
if (rtn.size()>0 && rtn.last().inject(rtn.last().size(), function(s, v) {
s+=v.length;
return s;
}) + curSize <= width) {
rtn.last().push(val);
} else {
rtn.push([val]);
}
return rtn;
}).invoke("join", " ").join("\n");
}
// example usage
fitTextToWidth("This is a long string of text. Possible something that a character would say in an RPG dialog box. The function will return this string with '\\n' characters inserted when necessary, to keep the text less than 30 characters per line.", 30);
//-> This is a long string of text.
// Possible something that a
// character would say in an RPG
// dialog box. The function will
// return this string with '\n'
// characters inserted when
// necessary, to keep the text
// less than 30 characters per
// line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment