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.
Example. 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.
Tip 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
Original left alone. 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.
Here We replace all 3-letter patterns with the first two letters "ca." We replace them with the word "test."
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 characters. For URLs, we often need to handle special characters like "#" and spaces. We can use replace() for these, but encodeURIComponent is simpler and faster.
Replace notes. With replace we can use regular expression and string arguments. We investigated the performance of these methods.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2023 (edit).