js实现replace
实现 JavaScript 的 replace 功能
JavaScript 的 replace 方法用于在字符串中替换匹配的子串或正则表达式。以下是几种常见的实现方式和使用场景:
基本字符串替换
使用字符串作为第一个参数,仅替换第一次出现的匹配项:

let str = "Hello World";
let newStr = str.replace("World", "Universe");
console.log(newStr); // 输出: Hello Universe
使用正则表达式全局替换
通过正则表达式配合 g 标志实现全局替换:
let str = "apple, orange, apple";
let newStr = str.replace(/apple/g, "banana");
console.log(newStr); // 输出: banana, orange, banana
使用函数作为替换参数
可以传入函数进行动态替换:

let str = "Price: $10";
let newStr = str.replace(/\$(\d+)/, (match, p1) => {
return `$${parseInt(p1) * 1.1}`;
});
console.log(newStr); // 输出: Price: $11
特殊替换模式
使用 $ 符号的特殊替换模式:
let str = "Doe, John";
let newStr = str.replace(/(\w+), (\w+)/, "$2 $1");
console.log(newStr); // 输出: John Doe
自定义 replace 函数
如果需要自定义替换逻辑,可以实现类似功能:
function customReplace(str, searchValue, replaceValue) {
if (typeof searchValue === 'string') {
return str.split(searchValue).join(replaceValue);
} else if (searchValue instanceof RegExp) {
return str.replace(searchValue, replaceValue);
}
return str;
}
let str = "test test test";
console.log(customReplace(str, 'test', 'example')); // 输出: example example example
这些方法覆盖了 JavaScript 中 replace 的主要使用场景,包括简单替换、正则替换和函数替换等高级用法。






