Skip to content

Commit

Permalink
fix: truncatewords should use at least one word, #537
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Oct 21, 2022
1 parent 71a1dc6 commit 32f613f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/builtin/filters/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
4 changes: 4 additions & 0 deletions test/integration/builtin/filters/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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...')
Expand Down

0 comments on commit 32f613f

Please sign in to comment.