Replace
In Node.js, a string
can be changed in many ways. With replace, we swap a part of a string
with another substring. The result is copied into a new string
.
For optimization, replace is an important method to focus on. Often a replace()
call is used in a function's fast path. We can apply measures to optimize (or eliminate) replace.
With this string
method we replace the first instance of a substring with a replacement substring. The searching begins from the left part of the string
.
Replace
can be called multiple times on the same string
to replace many occurrences.var animals = "bird, cat, bird"; // Replace first instance of bird with frog. var result = animals.replace("bird", "frog"); console.log("REPLACE RESULT: " + result);REPLACE RESULT: frog, cat, bird
When we call replace()
the original string
is left alone. So a string
is not mutated in-place. A new copy is created—we can use both forms in our program.
var initial = "abc def ghi"; // Replace one part of the string. var result = initial.replace("abc", "xyz"); // The initial string is left unchanged. console.log("BEFORE: " + initial); console.log("AFTER REPLACE: " + result);BEFORE: abc def ghi AFTER REPLACE: xyz def ghi
Regex
Sometimes a more complex replacement method is needed. With Regex
we can replace a pattern. All matching patterns can be replaced with a "g" modifier.
var data = "cat cap city car"; console.log("BEFORE: " + data); // Replace all matching patterns with a string. // ... Remove the g to only replace the first match. var result = data.replace(/ca\w/g, "test"); console.log("PATTERN REPLACE: " + result);BEFORE: cat cap city car PATTERN REPLACE: test test city test
Replace
URL charactersFor URLs, we often need to handle special characters like "#" and spaces. We can use replace()
for these, but encodeURIComponent
is simpler and faster.
Replace
notesWith replace we can use regular expression and string
arguments. We investigated the performance of these methods.