Go Back
Refer: Medium - Replace
Describe
Implement Replace<S, From, To>
which replace the string From
with To
once in the given string S
.
For example
code snippetCopytypescripttype replaced = Replace<'types are fun!', 'fun', 'awesome'> // expected to be 'types are awesome!'
Test Cases
code snippetCopytypescriptimport { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<Replace<'foobar', 'bar', 'foo'>, 'foofoo'>>,
Expect<Equal<Replace<'foobarbar', 'bar', 'foo'>, 'foofoobar'>>,
Expect<Equal<Replace<'foobarbar', '', 'foo'>, 'foobarbar'>>,
Expect<Equal<Replace<'foobarbar', 'bra', 'foo'>, 'foobarbar'>>,
Expect<Equal<Replace<'', '', ''>, ''>>,
]
Solution
code snippetCopytypescripttype Replace<S extends string, From extends string, To extends string> = From extends ''
? S
: S extends `${infer P}${From}${infer K}`
? `${P}${To}${K}`
: S