Last active
September 18, 2020 19:48
-
-
Save andyford/c394edef7b08f67b523bd55db8bc4561 to your computer and use it in GitHub Desktop.
collapse whitespace and newlines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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"); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just ran into a situation where I wanted to insert actual HTML
ptags (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