Skip to content

Commit

Permalink
feat: add replace_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 6f0a680 commit b4d1e27
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/filters/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ export function replace_first (v: string, arg1: string, arg2: string) {
return stringify(v).replace(String(arg1), arg2)
}

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

export function truncate (v: string, l = 50, o = '...') {
v = stringify(v)
if (v.length <= l) return v
Expand Down
10 changes: 10 additions & 0 deletions test/integration/filters/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,4 +202,14 @@ 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('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" }}',
'Take my protein pills and put my helmet on')
})
})
})

0 comments on commit b4d1e27

Please sign in to comment.