Skip to content

Commit 32f613f

Browse files
committed
fix: truncatewords should use at least one word, #537
1 parent 71a1dc6 commit 32f613f

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

src/builtin/filters/string.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,10 @@ export function truncate (v: string, l = 50, o = '...') {
8989
return v.substring(0, l - o.length) + o
9090
}
9191

92-
export function truncatewords (v: string, l = 15, o = '...') {
92+
export function truncatewords (v: string, words = 15, o = '...') {
9393
const arr = stringify(v).split(/\s+/)
94-
let ret = arr.slice(0, l).join(' ')
95-
if (arr.length >= l) ret += o
94+
if (words <= 0) words = 1
95+
let ret = arr.slice(0, words).join(' ')
96+
if (arr.length >= words) ret += o
9697
return ret
9798
}

test/integration/builtin/filters/string.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,10 @@ describe('filters/string', function () {
172172
})
173173
})
174174
describe('truncatewords', function () {
175+
it('should truncate to 1 words if less than 1', function () {
176+
return test('{{ "Ground control to Major Tom." | truncatewords: 0 }}',
177+
'Ground...')
178+
})
175179
it('should truncate when too many words', function () {
176180
return test('{{ "Ground control to Major Tom." | truncatewords: 3 }}',
177181
'Ground control to...')

0 commit comments

Comments
 (0)