yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

000017-medium-replaceall #17

Open yunliuyan opened 1 year ago

yunliuyan commented 1 year ago

ReplaceAll 中等 #template-literal

by Anthony Fu @antfu

接受挑战    English 日本語 한국어

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

例如

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

返回首页 分享你的解答 查看解答
yunliuyan commented 1 year ago

思路

基于replace进行递归

代码实现

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

type replaced = ReplaceAll<'t y p e s', ' ', ''>; // 'types'
Janice-Fan commented 1 year ago
type ReplaceAll<S extends string, From extends string, To extends string> 
= From extends '' ? S : S extends `${infer X1}${From}${infer X2}` ? 
`${X1}${To}${ReplaceAll<X2, From, To>}` : S;

type replaceAll = ReplaceAll<'t y p e s', ' ', ''> // 期望是 'types'
liangchengv commented 1 year ago
type ReplaceAll<S extends string, From extends string, To extends string> = 
From extends '' ? S : S extends `${infer U}${From}${infer R}`? `${U}${To}${ReplaceAll<R, From, To>}` : S;

type replaced = ReplaceAll<'t y p e s', ' ', ''>
wudu8 commented 1 year ago
type MyReplaceAll<S extends string, From extends string, To extends string> = S extends '' ? '' : S extends `${infer L}${From}${infer R}` ? `${L}${To}${MyReplaceAll<`${R}`, From, To>}` : S;

type replacedTest = MyReplaceAll<'t y p e s', ' ', ''>; // 'types'