1 decade ago by Kingsley
I needed to wrap some text so it fitted into a box shape rather than running all the way across the screen. This is the solution I came up with:
You basically supply the text, the max length and optionally a boolean for the cut option which is false by default. Cut just means instead of wrapping by word it will split the word up and wrap by char. But I guess most of the time wrapping by word is more readable.
WordWrap = ig.Class.extend({
text:"",
maxWidth:100,
cut: false,
init:function (text, maxWidth, cut) {
this.text = text;
this.maxWidth = maxWidth;
this.cut = cut;
},
wrap:function(){
var regex = '.{1,' +this.maxWidth+ '}(\\s|$)' + (this.cut ? '|.{' +this.maxWidth+ '}|.+$' : '|\\S+?(\\s|$)');
return this.text.match( RegExp(regex, 'g') ).join( '\n' );
}
});
var wrapper = new WordWrap('some length text',25);
wrapper.wrap();
You basically supply the text, the max length and optionally a boolean for the cut option which is false by default. Cut just means instead of wrapping by word it will split the word up and wrap by char. But I guess most of the time wrapping by word is more readable.
