String.replace() substitutes matched text. Give it a regular expression to match a pattern rather than a fixed string; a global regex replaces every match. section 10.5
A replacement callback lets each match produce its own replacement:
- It receives the full match, captures, match index, and source string; its return value becomes the replacement. section 10.5
- For example, a callback can uppercase the letter after each dash to convert a dashed name to camel case. section 10.5
Listing 10.9. Converting a dashed string to camel case
function upper(all,letter) { return letter.toUpperCase(); } #A
assert("border-bottom-width".replace(/-(\w)/g,upper) #B
=== "borderBottomWidth",
"Camel cased a hyphenated string.");
A callback-based example converts a hyphenated string to camel case. section 10.5
Listing 10.10. A technique for compressing a query string
function compress(source) {
const keys = {}; #A
source.replace(
/([^=&]+)=([^&]*)/g,
function(full, key, value) { #B
keys[key] =
(keys[key] ? keys[key] + "," : "") + value;
return "";
}
);
const result = []; #C
for (let key in keys) { #C
result.push(key + "=" + keys[key]); #C
} #C
return result.join("&"); #D
}
assert(compress("foo=1&foo=2&blah=a&blah=b&foo=3") ===
"foo=1,2,3&blah=a,b",
"Compression is OK!");
This example uses a global regex and callback to collect repeated query-string values. section 10.5





