Replace occurrence in a string in TypeScript

Example of Replace use

Today we discuss Replace

We need to remove one occurrence in the string and place instead the different value

Letโ€™s do that ๐Ÿš€

Replace occurrence

Letโ€™s first find occurrence within a string and replace it with the different value:

Replace, version 1

We donโ€™t know start and end but know for sure that From is in the string S.

Thatโ€™s not the perfect solution though: https://tsplay.dev/WGnp9m

So when the input string S is empty, we want to have it as a result. Letโ€™s replace never with S:

Replace, version 2

Still we missed the case where we try to replace empty From: https://tsplay.dev/WYJabw

Here we donโ€™t need to do anything:

Solution of Replace

The solution is available here: https://tsplay.dev/wgrVMW

Have a wonderful evening โ˜•๏ธ

typescriptmedium

Let's chat and have fun ๐Ÿง‘โ€๐Ÿ’ป๐Ÿ‘ฉโ€๐Ÿ’ป

No more often than once a week I write ๐Ÿ“„ about TypeScript ๐Ÿ’ช, video playback ๐Ÿ“บ and frontend related topics. You can unsubscribe in any time โ†˜๏ธ

ยฉ 2021, Built with Gatsby