[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll [Back]  [Original]

String.prototype.replaceAll() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

String.prototype.replaceAll()

Baseline

20208

replaceAll() String pattern replacement pattern RegExp replacement

const paragraph = "I think Ruth's dog is cuter than your dog!";

console.log(paragraph.replaceAll("dog", "monkey"));
// : "I think Ruth's monkey is cuter than your monkey!"

// Global flag required when calling replaceAll with regex
const regex = /Dog/gi;
console.log(paragraph.replaceAll(regex, "ferret"));
// : "I think Ruth's ferret is cuter than your ferret!"

js
replaceAll(pattern, replacement)

pattern

Symbol.replace Symbol.replace

regexp (g) TypeError

replacement

String.prototype.replace()

TypeError

pattern (g) flags "g"

replace() replace() RegExp() RegExp.escape() replaceAll()

js
function unsafeRedactName(text, name) {
  return text.replace(new RegExp(name, "g"), "[REDACTED]");
}
function semiSafeRedactName(text, name) {
  return text.replaceAll(name, "[REDACTED]");
}
function superSafeRedactName(text, name) {
  // only match at word boundaries
  return text.replaceAll(
    new RegExp(`\\b${RegExp.escape(name)}\\b`, "g"),
    "[REDACTED]",
  );
}

let report =
  "A hacker called ha.*er used special characters in their name to breach the system.";

console.log(unsafeRedactName(report, "ha.*er")); // "A [REDACTED]s in their name to breach the system."
console.log(semiSafeRedactName(report, "ha.*er")); // "A hacker called [REDACTED] used special characters in their name to breach the system."

report = "A hacker called acke breached the system.";

console.log(semiSafeRedactName(report, "acke")); // "A h[REDACTED]r called [REDACTED] breached the system."
console.log(superSafeRedactName(report, "acke")); // "A hacker called [REDACTED] breached the system."

pattern Symbol.replace RegExp replacement replaceAll() replaceAll() [Symbol.replace]() replace() pattern split() UTF-16

js
"xxx".replaceAll("", "_"); // "_x_x_x_"

sticky replaceAll() RegExp.prototype[Symbol.replace]()

replaceAll()

js
"aabbcc".replaceAll("b", ".");
// 'aa..cc'

js
"aabbcc".replaceAll(/b/, ".");
// TypeError: replaceAll must be called with a global RegExp

js
"aabbcc".replaceAll(/b/g, ".");
("aa..cc");

ECMAScript 2027 LanguageSpecification
# sec-string.prototype.replaceall


Web Proxy Viewer  |  New URL  |  Original Page