Skip to content

Instantly share code, notes, and snippets.

@andyford
Last active September 18, 2020 19:48
Show Gist options
  • Select an option

  • Save andyford/c394edef7b08f67b523bd55db8bc4561 to your computer and use it in GitHub Desktop.

Select an option

Save andyford/c394edef7b08f67b523bd55db8bc4561 to your computer and use it in GitHub Desktop.
collapse whitespace and newlines
// use with CSS rule: 'white-space: pre-wrap;'
const collapsedString = originalString
// remove leading and trailing whitespace
.trim()
// remove spaces before/after newlines - https://stackoverflow.com/a/5568828 (in comment by ridgerunner)
.replace(/^[^\S\r\n]+|[^\S\r\n]+$/gm, "")
// collapse all spaces down to one space - https://stackoverflow.com/a/1981366
.replace(/ +/g, " ")
// collapse 3+ newlines down to 2 newlines (preserving paragraphs) - https://stackoverflow.com/a/10965543
.replace(/\n\s*\n\s*\n/g, "\n\n");
@andyford
Copy link
Author

Just ran into a situation where I wanted to insert actual HTML p tags (when outputting content in an RSS feed). In this case, this package (or the regex it uses) is handy https://github.com/ryanburgess/lines-to-paragraphs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment