Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates: Respect spaces in new lines #4704

Merged
merged 1 commit into from Oct 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 5 additions & 4 deletions server/lib/sanitize-html.ts
Expand Up @@ -123,12 +123,13 @@ export const generateSummaryForHTML = (content: string, maxLength = 255): string
return null;
}

// Replace all new lines by separators
const withoutBR = content.replace(/<br\/?>/, ' ');
const separatedTitles = withoutBR.replace(/<\/h3>/, '</h3> · ');
const cleanStr = content
.replace(/(<br\/?>)|(\n)/g, ' ') // Replace all new lines by separators
.replace(/<\/p>/g, '</p> ') // Add a space after each paragraph to mark the separation
.replace(/<\/h3>/g, '</h3> · '); // Separate titles from then rest with a midpoint;

// Sanitize: `<li><strong> Test with spaces </strong></li>` ==> `<strong> Test with spaces </strong>`
const sanitized = sanitizeHTML(separatedTitles, optsSanitizeSummary);
const sanitized = sanitizeHTML(cleanStr, optsSanitizeSummary);

// Trim: `<strong> Test with spaces </strong>` ==> <strong>Test with spaces</strong>
const trimmed = sanitized.trim().replace('\n', ' ').replace(/\s+/g, ' ');
Expand Down
15 changes: 15 additions & 0 deletions test/server/lib/sanitize-html.test.js
Expand Up @@ -151,6 +151,21 @@ describe('server/lib/sanitize-html', () => {
);
});

it('Replaces newlines by spaces', () => {
expect(generateSummaryForHTML(`Hello\nWorld<br/><br/>!\n\n\nOnly one space`, 40)).to.eq(
'Hello World ! Only one space',
);

expect(
generateSummaryForHTML(
`<p>After a much ado, we created an easy way to donate to <a href="https://sagemath.org" target="_blank">SageMath</a> project.</p><p>Donations are US tax (IRC 501(c)(6)) deductible. </p>`,
240,
),
).to.eq(
'After a much ado, we created an easy way to donate to <a href="https://sagemath.org" target="_blank">SageMath</a> project. Donations are US tax (IRC 501(c)(6)) deductible.',
);
});

it('Truncating tags in middle works as expected', () => {
expect(generateSummaryForHTML("I'd like to say <strong>Hello World</strong>", 20)).to.to.eq("I'd like to say...");
});
Expand Down