Skip to content

Instantly share code, notes, and snippets.

@tylor
Created April 9, 2020 17:49
Show Gist options
  • Save tylor/0da7340ead85dad062c625893093fa16 to your computer and use it in GitHub Desktop.
Save tylor/0da7340ead85dad062c625893093fa16 to your computer and use it in GitHub Desktop.
JavaScript JS port of Ruby word_wrap
// Port of Rails word_wrap(): https://github.com/rails/rails/blob/master/actionview/lib/action_view/helpers/text_helper.rb#L260
// rstrip using: https://stackoverflow.com/a/1418059
const word_wrap = (text, line_width, break_sequence) => {
line_width = line_width || 80
break_sequence = break_sequence || "\n"
return text.split("\n").map((line) => {
return line.length > line_width ? line.replace(new RegExp(`(.{1,${line_width}})(\\s+|$)`, 'gm'), `$1${break_sequence}`).replace(/^\s+|\s+$/g, '') : line
}).join("\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment