TypeScript - replace all occurrences of string
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:
const input: string = 'text-1 text-2 text-3';
const output: string = input.split('text').join('____');
console.log(output); // ____-1 ____-2 ____-3
Â
More detailed and grouped solutions are placed below.
1. Text splitting and joining example
This section shows how to split string by some text and later join it putting new text beetwen.
const input: string = 'text-1 text-2 text-3';
const searchText: string = 'text';
const newText: string = '____';
const output: string = input.split(searchText).join(newText);
console.log(output); // ____-1 ____-2 ____-3
2. Regular expression based examples
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
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: .*+?^=!:${}()|[]/\
.
const ESCAPE_EXPRESSION: RegExp = /([.*+?^=!:${}()|\[\]\/\\])/g;
function escapeExpression(expressionText: string): RegExp {
expressionText = expressionText.replace(ESCAPE_EXPRESSION, '\\$1');
return new RegExp(expressionText, 'g'); // global searching flag
}
function replaceAll(text: string, what: string, to: string): string {
const whatExpression: RegExp = escapeExpression(what);
return text.replace(whatExpression, to);
}
// Usage example:
const inputText: string = 'This? is? my text.';
const searchText: string = 'is?';
const newText: string = '__';
const outputText: string = replaceAll(inputText, searchText, newText);
console.log(outputText); // Output: Th__ __ my text.
Note:Â
escapeExpression
function escapes all characters from regular expression pattern.
b)Â Unsafe approach
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.
const inputText: string = 'This? is? my text.';
const searchText: string = 'is\\?'; // escaped ? character
const newText: string = '__';
const searchRegex: RegExp = new RegExp(searchText, 'g'); // global searching flag
const outputText: string = inputText.replace(searchRegex, newText);
console.log(outputText); // Output: Th__ __ my text.