String replace Examples
This page was last reviewed on Dec 13, 2023.
Dot Net Perls
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 13, 2023 (edit).
© 2007-2024 Sam Allen.