mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-20 06:50:47 -07:00
fix(truncatewords): ignore leading whitespace when counting words (#954)
str.split(/\s+/) yields a leading empty element when the input starts with whitespace, so that element was counted as a word and joined back into the output: " Ground control to Major Tom." truncated to 3 words returned " Ground control..." instead of "Ground control to...". Ruby Liquid splits in awk mode, which discards leading whitespace but keeps trailing whitespace, so trimStart matches it and trim would not.
This commit is contained in:
@@ -180,7 +180,7 @@ export function truncatewords (this: FilterImpl, v: string, words = 15, o = '...
|
||||
const str = stringify(v)
|
||||
o = stringify(o)
|
||||
this.context.memoryLimit.use(str.length + o.length)
|
||||
const arr = str.split(/\s+/)
|
||||
const arr = str.trimStart().split(/\s+/)
|
||||
if (words <= 0) words = 1
|
||||
let ret = arr.slice(0, words).join(' ')
|
||||
if (arr.length >= words) ret += o
|
||||
|
||||
@@ -233,6 +233,12 @@ describe('filters/string', function () {
|
||||
it('should default len to 15', function () {
|
||||
return test('{{ "1 2 3 4 5 6 7 8 9 a b c d e f" | truncatewords }}', '1 2 3 4 5 6 7 8 9 a b c d e f...')
|
||||
})
|
||||
it('should ignore leading whitespace when counting words', function () {
|
||||
return test('{{ " Ground control to Major Tom." | truncatewords: 3 }}', 'Ground control to...')
|
||||
})
|
||||
it('should keep trailing whitespace when not truncating', function () {
|
||||
return test('{{ "1 2 3 " | truncatewords: 5 }}', '1 2 3 ')
|
||||
})
|
||||
})
|
||||
describe('remove_last', function () {
|
||||
it('should remove the last occurrence of substring', function () {
|
||||
|
||||
Reference in New Issue
Block a user