From f9a1316d161f4f20018c833160f42dfcf0cde507 Mon Sep 17 00:00:00 2001 From: spokodev Date: Thu, 9 Jul 2026 15:41:46 +0100 Subject: [PATCH] fix(filters): return empty for out-of-range slice begin or negative length (#928) Ruby/Shopify `slice` returns nil (rendered as an empty string or array) when the begin offset falls outside the negative range or when the length is negative. liquidjs forwarded the adjusted indices straight to Array/String.prototype.slice, whose own negative-index handling produced non-empty, incorrect output: {{ "hello" | slice: -10, 2 }} => "he" (expected "") {{ "Liquid" | slice: 1, -2 }} => "iqui" (expected "") Guard the adjusted begin and the length before slicing. --- src/filters/array.ts | 1 + test/integration/filters/array.spec.ts | 3 +++ 2 files changed, 4 insertions(+) diff --git a/src/filters/array.ts b/src/filters/array.ts index 57a7d802d..09761f87c 100644 --- a/src/filters/array.ts +++ b/src/filters/array.ts @@ -114,6 +114,7 @@ export function slice (this: FilterImpl, v: T[] | string, begin: number, leng if (isNil(v)) return [] if (!isArray(v)) v = stringify(v) begin = begin < 0 ? v.length + begin : begin + if (begin < 0 || length < 0) return isArray(v) ? [] : '' this.context.memoryLimit.use(length) return isArray(v) ? Array.prototype.slice.call(v, begin, begin + length) diff --git a/test/integration/filters/array.spec.ts b/test/integration/filters/array.spec.ts index b9212686f..307c5c99b 100644 --- a/test/integration/filters/array.spec.ts +++ b/test/integration/filters/array.spec.ts @@ -288,6 +288,9 @@ describe('filters/array', function () { it('should slice substr by -2,2', () => test('{{ "abc" | slice: -2, 2 }}', 'bc')) it('should support array', () => test('{{ "1,2,3,4" | split: "," | slice: 1,2 | join }}', '2 3')) it('should return empty array for nil value', () => test('{{ nil | slice: 0 }}', '')) + it('should return empty when begin is out of negative range', () => test('{{ "hello" | slice: -10, 2 }}', '')) + it('should return empty when length is negative', () => test('{{ "Liquid" | slice: 1, -2 }}', '')) + it('should return empty array when begin is out of negative range', () => test('{{ "1,2,3,4,5" | split: "," | slice: -10, 2 | join: "," }}', '')) }) describe('sort', function () { it('should support sort', function () {