HomeSearch

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 Regex description: ca Letters c and a \w Word character g Match globally (all instances)

Replace performance.

In modern browsers, JavaScript regular expressions are well-optimized. I tested two replace calls on strings versus one replace call with a regular expression.

Result: It is faster in Chrome to use one regular expression than two replace string calls.

So: Regular expressions are about the same speed as simple string replacements.

JavaScript program that uses replace, two calls var x1 = performance.now(); var v = "cat and dog and dog"; for (var i = 0; i < 1000000; i++) { var result = v.replace("dog", "bird"); result = result.replace("dog", "bird"); if (result != "cat and bird and bird") { document.write("?"); } } var x2 = performance.now(); document.title = x2 - x1; JavaScript program that uses replace, regular expression var x1 = performance.now(); var v = "cat and dog and dog"; for (var i = 0; i < 1000000; i++) { var result = v.replace(/dog/g, "bird"); if (result != "cat and bird and bird") { document.write("?"); } } var x2 = performance.now(); document.title = x2 - x1; Output 570.65 ms replace, replace 242.50 ms replace(//g)

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 x1 method (which is poorly-named) replaces three characters globally with a space.

Version 2: The x1 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 no fast path function x1(x) { // Replace these characters on all strings. x = x.replace(/[\.\-\?]/g, ' '); return x; } var time1 = performance.now(); for (var i = 0; i < 1000000; i++) { x1("The cat is cute") x1("There...is a cat") x1("Fast path") x1("Not-fast-path") } var time2 = performance.now(); var elapsed = time2 - time1; document.title = elapsed + " ms/" + x1("abc.123"); JavaScript program that uses replace with fast path function x1(x) { // First see if characters need replacing. 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 time1 = performance.now(); for (var i = 0; i < 1000000; i++) { x1("The cat is cute") x1("There...is a cat") x1("Fast path") x1("Not-fast-path") } var time2 = performance.now(); var elapsed = time2 - time1; document.title = elapsed + " ms/" + x1("abc.123"); Output 957.47 ms/abc 123 no fast path 440.38 ms/abc 123 has fast path

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.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.