7
devios1
7y

Inherited a codebase that implements its own word wrapping for receipt printing. Problem is it's putting an extra space at the end of each line.

I open up the implementation, expecting it to be a relatively simple fix, until I see this…

var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match(RegExp(regex, 'g')).join(linebreak);

Comments
  • 0
    for(String s:lines) s.subString(s.length()-1);
  • 0
    width += 1 ?
  • 1
    The regex makes sense, but it doesn't trim the lines. What it does is select up to (width) characters followed by a space or end of line, and adds a newline after it. Makes sense for word wrapping - but this preserves the space on which it wrapped.

    return str.match(new RegExp(regex, 'g')).map(s => s.trim()).join(linebreak);

    This should fix it.
  • 2
    @configurator My point was that whatever efficiency may be gained by implementing a word wrap using regex is quickly nullified by the cryptic code it requires.

    I know regex basics, but this is beyond me, and as I imagine, probably most people.

    I ended up doing what @BindView suggested and just trimmed the lines afterward.

    To me, this is not what regex is for. Regex is for finding pieces of a larger string that match a certain pattern, like pulling out email addresses from a block of text, or validating a phone number.
  • 1
    @devios1 agreed,this is an abomination. What I suggested does that too, except using trim rather than substring because there's not a guaranteed space there.

    Just thought I could help because I can actually read and understand this regex.
  • 1
    @configurator Thanks for that; I didn't see your edit. Yeah I actually am using trim as well for the same reason, and since I couldn't understand the regex enough to know if there would be space guaranteed or not. ;)
  • 2
    yay i was useful
Add Comment