Skip to content

Instantly share code, notes, and snippets.

@ChrisVilches
Created August 23, 2018 20:55
Show Gist options
  • Save ChrisVilches/16cccd2d9e4f0f04f8abbe727677e0c7 to your computer and use it in GitHub Desktop.
Save ChrisVilches/16cccd2d9e4f0f04f8abbe727677e0c7 to your computer and use it in GitHub Desktop.
Converts a multiline string into a <p>...</p> separated string for HTML use.
function toParagraphs(string){
return string.split(/[\r?\n]+/g)
.map(p => p.trim())
.filter(p => p.length > 0)
.map(p => `<p>${p}</p>`)
.join("");
}
// Tests
let testData = [
[` 456 `, "<p>456</p>"],
[`a`, "<p>a</p>"],
[`a\nb `, "<p>a</p><p>b</p>"],
[` `, ""],
[`\n\n`, ""],
[` \n \t \n `, ""],
[`\na`, "<p>a</p>"],
[`a\n`, "<p>a</p>"],
[`a\n\n`, "<p>a</p>"],
[`\na\n`, "<p>a</p>"],
[`\na\n\n`, "<p>a</p>"],
[`\na\t\n\t\nb\t`, "<p>a</p><p>b</p>"]
];
let testDataMultiline = [
[`
1
2
3
`, "<p>1</p><p>2</p><p>3</p>"],
[`a
b `, "<p>a</p><p>b</p>"],
[`
AAA
11
22222
3
44
5
6
777
`, "<p>AAA</p><p>11</p><p>22222</p><p>3</p><p>44</p><p>5</p><p>6</p><p>777</p>"]
];
testDataMultiline.concat(testData).map(d => {
console.assert(toParagraphs(d[0]) === d[1]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment