| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll | [Back] [Original] |
Get to know MDN better
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!"
replaceAll(pattern, replacement)
pattern Symbol.replace Symbol.replace
regexp (g) TypeError
replacementreplace() replace() RegExp() RegExp.escape() replaceAll()
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
"xxx".replaceAll("", "_"); // "_x_x_x_"
sticky replaceAll() RegExp.prototype[Symbol.replace]()
"aabbcc".replaceAll("b", ".");
// 'aa..cc'
"aabbcc".replaceAll(/b/, ".");
// TypeError: replaceAll must be called with a global RegExp
"aabbcc".replaceAll(/b/g, ".");
("aa..cc");
| ECMAScript 2027 LanguageSpecification # sec-string.prototype.replaceall |
Stringanchor()at()big()blink()bold()charAt()charCodeAt()codePointAt()concat()endsWith()fixed()fontcolor()fontsize()includes()indexOf()isWellFormed()italics()lastIndexOf()link()localeCompare()match()matchAll()normalize()padEnd()padStart()repeat()replace()replaceAll()search()slice()small()split()startsWith()strike()sub()substr()substring()sup()toLocaleLowerCase()toLocaleUpperCase()toLowerCase()toString()toUpperCase()toWellFormed()trim()trimEnd()trimStart()valueOf()[Symbol.iterator]()Object/Function| Web Proxy Viewer | New URL | Original Page |