String.prototype.replace() 是字符串處理的核心方法,語法為 str.replace(regexp|substr, newSubstr|function)。第二個參數支持函數,開啟了動態替換的強大能力。
const re = /你妹|fuck|你大爺|萌萌/g;
'我要看你妹'.replace(re, '*'); // "我要看*"
但這會將所有敏感詞統一替換為單個 *,無法保持原長度。
回調函數接收匹配到的子串,返回值作為替換文本:
const re = /你妹|fuck|你大爺|萌萌/g;
const result = '我要看你妹,不行,你大爺'.replace(re, match => {
return '*'.repeat(match.length);
});
console.log(result); // "我要看**,不行,****"
完整簽名:function(match, p1, p2, ..., offset, string)
match:匹配的完整子串p1, p2...:分組捕獲內容(若正則含捕獲組)offset:匹配在原字符串中的索引string:原字符串const template = '你好,{{name}}!今天是 {{date}}。';
const data = { name: '張三', date: '2024-01-15' };
const output = template.replace(/\{\{(\w+)\}\}/g, (_, key) => data[key] || '');
console.log(output); // "你好,張三!今天是 2024-01-15。"
g 標誌時僅替換首次匹配。$$、$&、$`、$'、$n(分組引用)。善用 replace 回調函數,能優雅解決動態替換、模板渲染、數據脫敏等需求,是前端工程師必備的字符串處理技能。