Word Wrapping for JavaScript

5.1.1 · active · verified Sun Apr 19

wordwrapjs is a lightweight and versatile JavaScript library designed for word-wrapping plain text within specified column widths. Currently at version 5.1.1, it provides a stable and efficient solution for text formatting across various JavaScript environments. The library supports Node.js (both CommonJS and ECMAScript Modules), modern web browsers (via ESM imports), and older browser environments (via a global `window.wordwrapjs` object), enabling broad compatibility without requiring transpilation. Its API offers methods to wrap text into a single string or an array of lines, with options to force long words to break and control line trimming. The project emphasizes plain text processing, focusing on core word-wrapping logic rather than rich text features. Releases appear stable, with infrequent major version bumps, indicating a mature and well-tested codebase.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic word wrapping with `wrap` and `lines` methods, including options for breaking long words and handling URLs. It shows the difference between breaking and not breaking long words for a given width.

import wordwrap from 'wordwrapjs'

const longText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'

// Wrap text to a 30-character width, allowing long words to break
const wrappedText = wordwrap.wrap(longText, { width: 30, break: true })
console.log('--- Wrapped Text (width 30, break: true) ---\n' + wrappedText)

const url = 'https://this-is-a-very-long-url-that-exceeds-the-column-width.com/path/to/resource'

// Wrap a long URL into lines, forcing breaks
const urlLines = wordwrap.lines(url, { width: 25, break: true })
console.log('\n--- Wrapped URL (width 25, break: true) ---')
urlLines.forEach(line => console.log(line))

// Wrap without forcing breaks (default behavior for long words)
const noBreakLines = wordwrap.lines(url, { width: 25 })
console.log('\n--- Wrapped URL (width 25, no break) ---')
noBreakLines.forEach(line => console.log(line))

view raw JSON →