替换换行符为 <br> (#1523)

close #1522
This commit is contained in:
Henry Wang
2019-02-19 22:45:29 +08:00
committed by DIYgod
parent 783a005ec6
commit 7a0f3e3eb7
3 changed files with 35 additions and 1 deletions
+13 -1
View File
@@ -30,10 +30,11 @@ module.exports = async (ctx, next) => {
}
if (ctx.state.data) {
// trim title length
ctx.state.data.item &&
ctx.state.data.item.forEach((item) => {
if (item.title) {
item.title = item.title.trim();
// trim title length
for (let length = 0, i = 0; i < item.title.length; i++) {
length += Buffer.from(item.title[i]).length !== 1 ? 2 : 1;
if (length > config.titleLengthLimit) {
@@ -47,6 +48,17 @@ module.exports = async (ctx, next) => {
const itunes_duration = Math.floor(item.enclosure_length / 3600) + ':' + Math.floor((item.enclosure_length % 3600) / 60) + ':' + (((item.enclosure_length % 3600) % 60) / 100).toFixed(2).slice(-2);
item.itunes_duration = itunes_duration;
}
if (item.description) {
item.description = item.description
.trim()
.replace(/(\r\n|\r|\n)/g, '<br>')
.replace(/^(<br>| |<br\/>)+|(<br>| |<br\/>)+$/g, '');
}
if (item.author) {
item.author = item.author.trim();
}
});
}
+9
View File
@@ -23,7 +23,16 @@ module.exports = async (ctx) => {
link: `https://github.com/DIYgod/RSSHub/issues/0`,
author: `DIYgod0`,
});
} else if (ctx.params.id === 'linebreaker') {
item.push({
title: `Long Title `,
description: `<br> <br/> \r\n\r\n Description \n\r with \r\n newlines \r\n\r\n <br/> <br>`,
pubDate: new Date(`2018-3-1`).toUTCString(),
link: `https://github.com/DIYgod/RSSHub/issues/0`,
author: `DIYgod0`,
});
}
for (let i = 1; i < 6; i++) {
item.push({
title: `Title${i}`,
+13
View File
@@ -66,4 +66,17 @@ describe('template', () => {
const parsed = await parser.parseString(response.text);
expect(parsed.items[0].title.length).toBe(103);
});
it(`replace newlines with <br>`, async () => {
const response = await request.get('/test/linebreaker');
const parsed = await parser.parseString(response.text);
const test = parsed.items[0].content;
// line breakers should have been replaced with <br>
expect(test).not.toContain('\r');
expect(test).not.toContain('\n');
// content should not start with and/or end with <br>|<br/>, which are meaningless
expect(test).toEqual(expect.not.stringMatching(/^(<br>| |<br\/>)+|(<br>| |<br\/>)+$/g));
});
});