C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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
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)
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