Skip to content

ReplaceAll

约 315 字大约 1 分钟

2022-12-01

题目

Github: ReplaceAll

实现 ReplaceAll<S, From, To> 将一个字符串 S 中的所有子字符串 From 替换为 To

type replaced = ReplaceAll<'t y p e s', ' ', ''> // 期望是 'types'

解题思路

Replace 类似,在 Replace 挑战中,我们将字符串 S 拆分为 FFromR 三个部分, 然后对 From 进行替换, 在完成替换后,我们需要继续对 R 进行替换,直到 R 为不包含 From 的字符串。

答案

type ReplaceAll<S extends string, From extends string, To extends string> = 
  From extends ''
    ? S
    : S extends `${infer F}${From}${infer R}`
      ? `${F}${To}${ReplaceAll<R, From, To>}`
      : S

验证

type 
cases
= [
Expect
<
Equal
<
ReplaceAll
<'foobar', 'bar', 'foo'>, 'foofoo'>>,
Expect
<
Equal
<
ReplaceAll
<'foobar', 'bag', 'foo'>, 'foobar'>>,
Expect
<
Equal
<
ReplaceAll
<'foobarbar', 'bar', 'foo'>, 'foofoofoo'>>,
Expect
<
Equal
<
ReplaceAll
<'t y p e s', ' ', ''>, 'types'>>,
Expect
<
Equal
<
ReplaceAll
<'foobarbar', '', 'foo'>, 'foobarbar'>>,
Expect
<
Equal
<
ReplaceAll
<'barfoo', 'bar', 'foo'>, 'foofoo'>>,
Expect
<
Equal
<
ReplaceAll
<'foobarfoobar', 'ob', 'b'>, 'fobarfobar'>>,
Expect
<
Equal
<
ReplaceAll
<'foboorfoboar', 'bo', 'b'>, 'foborfobar'>>,
Expect
<
Equal
<
ReplaceAll
<'', '', ''>, ''>>,
]

参考