Skip to content

Commit

Permalink
feat: add remove_last filter
Browse files Browse the repository at this point in the history
  • Loading branch information
jg-rp authored and harttle committed Dec 2, 2022
1 parent b4d1e27 commit 6c3f1c1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/filters/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ export function remove_first (v: string, l: string) {
return stringify(v).replace(String(l), '')
}

export function remove_last (v: string, l: string) {
const str = stringify(v)
const pattern = String(l)
const index = str.lastIndexOf(pattern)
if (index === -1) return str
return str.substring(0, index) + str.substring(index + pattern.length + 1)
}

export function rstrip (str: string, chars?: string) {
if (chars) {
chars = escapeRegExp(stringify(chars))
Expand Down
12 changes: 11 additions & 1 deletion test/integration/filters/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,23 @@ describe('filters/string', 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...')
})
})
describe('remove_last', function () {
it('should remove the last occurrence of substring', function () {
return test('{{ "I strained to see the train through the rain" | remove_last: "rain" }}',
'I strained to see the train through the ')
})
it('should handle substring not found', function () {
return test('{{ "I strained to see the train through the rain" | remove_last: "no such thing" }}',
'I strained to see the train through the rain')
})
})
describe('replace_last', function () {
it('should replace the last occurrence of substring', function () {
return test('{{ "Take my protein pills and put my helmet on" | replace_last: "my", "your" }}',
'Take my protein pills and put your helmet on')
})
it('should handle substring not found', function () {
return test('{{ "Take my protein pills and put my helmet on" | replace_last: "nosuchthing", "your" }}',
return test('{{ "Take my protein pills and put my helmet on" | replace_last: "no such thing", "your" }}',
'Take my protein pills and put my helmet on')
})
})
Expand Down

0 comments on commit 6c3f1c1

Please sign in to comment.