JavaScript - replace all occurrences of string
In this article, we're going to have a look at different ways how to replace all text occurrences inside strings in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var input = 'text-1 text-2 text-3';
var output = input.split('text').join('____');
console.log(output); // ____-1 ____-2 ____-3
or:
// ONLINE-RUNNER:browser;
var input = 'text-1 text-2 text-3';
var output = input.replaceAll('text', '____');
console.log(output); // ____-1 ____-2 ____-3
Note:
The
replaceAll()
mehod was introduced in ES2021.
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 between.
// ONLINE-RUNNER:browser;
var input = 'text-1 text-2 text-3';
var searchText = 'text';
var newText = '____';
var output = input.split(searchText).join(newText);
console.log(output); // ____-1 ____-2 ____-3
2. Regular expression-based examples
This section shows how to replace all text occurrences with RexExp
object. By default String
replace
method used with expression replaces only one text occurrence. The solution to this problem is to add g
flag for the expression object.
a) Safe approach
This example shows how to replace all occurrences of any text. The solution presented in this section uses an escaped pattern as the text we are looking for. This approach is strongly recommended if the replaced text could contain expression control characters like: .*+?^=!:${}()|[]/\
.
// ONLINE-RUNNER:browser;
var ESCAPE_EXPRESSION = /([.*+?^=!:${}()|\[\]\/\\])/g;
function escapeExpression(expressionText) {
expressionText = expressionText.replace(ESCAPE_EXPRESSION, '\\$1');
return new RegExp(expressionText, 'g'); // global searching flag
}
function replaceAll(text, what, to) {
var whatExpression = escapeExpression(what);
return text.replace(whatExpression, to);
}
// Usage example:
var inputText = 'This? is? my text.';
var searchText = 'is?';
var newText = '__';
var outputText = replaceAll(inputText, searchText, newText);
console.log(outputText);
Note:
escapeExpression
function escapes all characters from regular expression pattern.
b) Unsafe approach
This example shows how to replace all text occurrences. It is recommended only when all replaced characters were escaped \\
before. The main advantage of this approach is the lack of unnecessary processing of replaced text.
// ONLINE-RUNNER:browser;
var inputText = 'This? is? my text.';
var searchText = 'is\\?'; // escaped ? character
var newText = '__';
var searchRegex = new RegExp(searchText, 'g'); // global searching flag
var outputText = inputText.replace(searchRegex, newText);
console.log(outputText );