Replace all occurrences in a string in TypeScript

Example of ReplaceAll use

Today we discuss ReplaceAll

We need to remove all occurrences in the string and place instead the different value

Letโ€™s start โณ

Replace all occurrences

Letโ€™s check the solution for Replace and adapt it for ReplaceAll:

Replace, solution

This solution substitutes From for To once: https://tsplay.dev/mA7ZXw

Letโ€™s do that as many times as required:

ReplaceAll, version 1

But if we call ReplaceAll recursively this way, we will do it incorrectly. Let me give an example:

Not working example for version 1

So instead of calling ReplaceAll for the whole string, letโ€™s do it for the rest of the string, or End:

Solution

Thank you for your time! โŒ›๏ธ

The final solution with test cases are available here: https://tsplay.dev/mplJBm

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