Languages
[Edit]
EN

TypeScript - replace all occurrences of string

0 points
Created by:
maciek211
425

In this article, we're going to have a look at different ways how to replace all text occurances inside string in TypeScript. The most common problem in Typescript is lack of replaceAll method.

Quick overlook:

 

More detailed and grouped solutions are placed below.

1. Text splitting and joining example

Edit

This section shows how to split string by some text and later join it putting new text beetwen.

2. Regular expression based examples

Edit

This section shows how to replace all text occurances with RexExp object. By default String replace method used with expression replaces only one text occurance. Solution of this problem is to add g flag for expression object.

a) Safe approach

Edit

This example shows how to replace all occurrences of any text. The solution presented in this section uses escaped pattern as text we are looking for. This approach is strongly recommended if replaced text could contain expression controll characters like: .*+?^=!:${}()|[]/\.

Note: escapeExpression function escapes all characters from regular expression pattern.

b) Unsafe approach

Edit

This example shows how to replace all text occurances. It is recommended only when all replaced characters were escaped with \\ before. Main advantage of this approach is lack of unnecessary processing of replaced text.

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join