pipr.tools

wrap

Hard-wrap text at N columns

Aa Text

Try it

stdin0 chars
stdout0 chars

Flags

--width number default: 80

Example

Hard-wrap a long line at 80 columns

Usage
$ echo "This is a very long line of text that should be wrapped at e..." | wrap
View source
(input, opts = {}) => {
      const w = parseInt(opts.width) || 80;
      return input
        .split("\n")
        .map((line) => {
          if (line.length <= w) return line;
          const wrapped = [];
          let remaining = line;
          while (remaining.length > w) {
            let breakAt = remaining.lastIndexOf(" ", w);
            if (breakAt <= 0) breakAt = w;
            wrapped.push(remaining.slice(0, breakAt));
            remaining = remaining.slice(breakAt).trimStart();
          }
          if (remaining) wrapped.push(remaining);
          return wrapped.join("\n");
        })
        .join("\n");
    }

Suggested Pipelines

Related Tools