Skip to content

Commit

Permalink
feat(string): add afterLast
Browse files Browse the repository at this point in the history
  • Loading branch information
innocenzi committed Aug 26, 2023
1 parent 02add38 commit 0e4f984
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, it } from 'vitest'
import { capitalize, ensureStartsWith, ensureEndsWith, toForwardSlashes, template, toBackSlashes, replaceFirst, replaceLast, before, beforeLast, after } from './string'
import { capitalize, ensureStartsWith, ensureEndsWith, toForwardSlashes, template, toBackSlashes, replaceFirst, replaceLast, before, beforeLast, after, afterLast } from './string'

it('template', () => {
expect(
Expand Down Expand Up @@ -176,3 +176,16 @@ it('after', () => {
expect(after('han0nah', 0)).toEqual('nah')
expect(after('han2nah', 2)).toEqual('nah')
})

it('afterLast', () => {
expect(afterLast('yvette', 'yve')).toEqual('tte')
expect(afterLast('yvette', 't')).toEqual('e')
expect(afterLast('ééé yvette', 't')).toEqual('e')
expect(afterLast('yvette', 'tte')).toEqual('')
expect(afterLast('yvette', 'xxxx')).toEqual('yvette')
expect(afterLast('yvette', '')).toEqual('yvette')
expect(afterLast('yv0et0te', '0')).toEqual('te')
expect(afterLast('yv0et0te', 0)).toEqual('te')
expect(afterLast('yv2et2te', 2)).toEqual('te')
expect(afterLast('----foo', '---')).toEqual('foo')
})
18 changes: 18 additions & 0 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,24 @@ export function after(str: string, separator: string | number) {
return str.slice(index + separator.toString().length)
}

/**
* Returns everything after the last occurrence of the given value.
*
* @category String
*/
export function afterLast(str: string, separator: string | number) {
if (separator.toString() === '') {
return str
}

const index = str.lastIndexOf(separator.toString())
if (index === -1) {
return str
}

return str.slice(index + separator.toString().length)
}

/**
* Replaces the first occurrence of a given value in a string.
*
Expand Down

0 comments on commit 0e4f984

Please sign in to comment.