From 32f613fb43e90f97364ee6a020589992dbb553cf Mon Sep 17 00:00:00 2001 From: Harttle Date: Sun, 25 Sep 2022 14:52:11 +0800 Subject: [PATCH] fix: truncatewords should use at least one word, #537 --- src/builtin/filters/string.ts | 7 ++++--- test/integration/builtin/filters/string.ts | 4 ++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/builtin/filters/string.ts b/src/builtin/filters/string.ts index 58bd9558f0..faf042bf90 100644 --- a/src/builtin/filters/string.ts +++ b/src/builtin/filters/string.ts @@ -89,9 +89,10 @@ export function truncate (v: string, l = 50, o = '...') { return v.substring(0, l - o.length) + o } -export function truncatewords (v: string, l = 15, o = '...') { +export function truncatewords (v: string, words = 15, o = '...') { const arr = stringify(v).split(/\s+/) - let ret = arr.slice(0, l).join(' ') - if (arr.length >= l) ret += o + if (words <= 0) words = 1 + let ret = arr.slice(0, words).join(' ') + if (arr.length >= words) ret += o return ret } diff --git a/test/integration/builtin/filters/string.ts b/test/integration/builtin/filters/string.ts index f099b3bde5..d530191ff7 100644 --- a/test/integration/builtin/filters/string.ts +++ b/test/integration/builtin/filters/string.ts @@ -172,6 +172,10 @@ describe('filters/string', function () { }) }) describe('truncatewords', function () { + it('should truncate to 1 words if less than 1', function () { + return test('{{ "Ground control to Major Tom." | truncatewords: 0 }}', + 'Ground...') + }) it('should truncate when too many words', function () { return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}', 'Ground control to...')