JavaScript replace Examples

Replace substrings with other substrings with the replace method. Use global replace.

Replace. 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.

An 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.Strings
Tip: Replace can be called multiple times on the same string to replace many occurrences.
JavaScript program that uses replace var animals = "bird, cat, bird"; // Replace first instance of bird with frog. var result = animals.replace("bird", "frog"); console.log("REPLACE RESULT: " + result); Output 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.
JavaScript program that shows replace copies string 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); Output 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."
JavaScript program that uses replace, Regex 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); Output BEFORE: cat cap city car PATTERN REPLACE: test test city test Pattern details: ca Letters c and a \w Word character g Match globally (all instances)

Replace fast path, benchmark. Even in modern browsers the replace() method has overhead. If we can avoid a replace call, we can improve program performance.
Version 1: The func1 method (which is poorly-named) replaces three characters globally with a space.
Version 2: The func2 method uses charCodeAt in a for-loop to see if anything needs replacing, and then replaces if needed.
Result: The benchmark has 4 string arguments, and only half need a replace call. So the version 2 method performs about twice as fast.
JavaScript program that uses replace with fast path function func1(x) { x = x.replace(/[\.\-\?]/g, ' '); return x; } function func2(x) { for (var i = 0;i < x.length;i++) { var code = x.charCodeAt(i); if (code == 46 || // Period. code == 46 || // Hyphen. code == 63) { // Question. // Replace the characters. x = x.replace(/[\.\-\?]/g, ' '); break; } } return x; } var x1 = performance.now(); // Version 1: replace these characters on all strings. for (var i = 0; i < 1000000; i++) { func1("The cat is cute") func1("There...is a cat") func1("Fast path") func1("Not-fast-path") } var x2 = performance.now(); // Version 2: first see if characters need replacing. for (var i = 0; i < 1000000; i++) { func2("The cat is cute") func2("There...is a cat") func2("Fast path") func2("Not-fast-path") } var x3 = performance.now(); // Results. console.log("TIME 1: " + (x2 - x1)); console.log("TIME 2: " + (x3 - x2)); Output TIME 1 (2019): 461.189 TIME 2: 280.570

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.encodeURI

Replace notes. With replace we can use regular expression and string arguments. We investigated the performance of these methods.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.