Replace occurrence in string literal type in TypeScript

Example of Replace use
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
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
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
Solution of Replace

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

Have a wonderful evening ☕️

typescript

Alexey Berezin

Senior Software Engineer, UK Global Talent 🇬🇧

The portrait photo of me

Thank you for reading my blog post! If you have any questions, suggestions, or just want to say hi, feel free to reach out in social networks, or via email. I would love to hear from you!

Comments