Skip to content

Commit

Permalink
feat(string): add replaceFirst
Browse files Browse the repository at this point in the history
  • Loading branch information
innocenzi committed Aug 26, 2023
1 parent 16588ec commit 38091c0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
18 changes: 17 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 } from './string'
import { capitalize, ensureStartsWith, ensureEndsWith, toForwardSlashes, template, toBackSlashes, replaceFirst } from './string'

it('template', () => {
expect(
Expand Down Expand Up @@ -125,3 +125,19 @@ it('capitalize', () => {
expect(capitalize('āÁĂÀ')).toEqual('Āáăà')
expect(capitalize('\a')).toEqual('A')
})

it('replaceFirst', () => {
// $this->assertSame('fooqux foobar', Str::replaceFirst('bar', 'qux', 'foobar foobar'));
// $this->assertSame('foo/qux? foo/bar?', Str::replaceFirst('bar?', 'qux?', 'foo/bar? foo/bar?'));
// $this->assertSame('foo foobar', Str::replaceFirst('bar', '', 'foobar foobar'));
// $this->assertSame('foobar foobar', Str::replaceFirst('xxx', 'yyy', 'foobar foobar'));
// $this->assertSame('foobar foobar', Str::replaceFirst('', 'yyy', 'foobar foobar'));
// $this->assertSame('1', Str::replaceFirst(0, '1', '0'));

expect(replaceFirst('bar', 'qux', 'foobar foobar')).toEqual('fooqux foobar')
expect(replaceFirst('bar?', 'qux?', 'foo/bar? foo/bar?')).toEqual('foo/qux? foo/bar?')
expect(replaceFirst('bar', '', 'foobar foobar')).toEqual('foo foobar')
expect(replaceFirst('xxx', 'yyy', 'foobar foobar')).toEqual('foobar foobar')
expect(replaceFirst('', 'yyy', 'foobar foobar')).toEqual('foobar foobar')
expect(replaceFirst(0, '1', '0')).toEqual('1')
})
11 changes: 11 additions & 0 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ export function ensureStartsWith(prefix: string, str: string) {
return str
}

/**
* Replaces the first occurrence of a given value in a string.
*/
export function replaceFirst(search: string | number, replace: string | number, str: string) {
if (search.toString() === '') {
return str
}

return str.replace(search.toString(), replace.toString())
}

/**
* Ensures the given string ends with the given suffix.
*
Expand Down

0 comments on commit 38091c0

Please sign in to comment.