📜  Lodash _.replace() 方法(1)

📅  最后修改于: 2023-12-03 14:44:02.918000             🧑  作者: Mango

Lodash _.replace() 方法

Lodash中的_.replace()方法是用于替换字符串中指定匹配项的方法。该方法可以接收三个参数:需要被替换的字符串、需要被替换的模式或字符串、用于替换的字符串或函数。

语法
_.replace(string, pattern, replacement)
参数
  • string (string): 需要被处理的字符串。
  • pattern (RegExp|string): 需要被替换的模式或字符串。
  • replacement (Function|string): 用于替换的字符串或函数。
返回值

该方法返回替换后的新字符串。

示例
const str = 'hello lodash';

// 替换字符串中的第一个匹配项
const result1 = _.replace(str, 'l', 'w');
console.log(result1);
// expected output: 'hewlo lodash'

// 替换字符串中所有的匹配项
const result2 = _.replace(str, /l/g, 'w');
console.log(result2);
// expected output: 'hewwo do dash'

// 使用函数作为替换值
const result3 = _.replace(str, /l/g, (match, offset) => `${match}-${offset}`);
console.log(result3);
// expected output: 'he(l-2)(l-3)o do(l-8)ash'

可以看到,_.replace()方法非常灵活,可以用于替换单个或多个匹配项,也可以使用函数进行替换。

注意,该方法不会直接修改原字符串,而是返回一个替换后的新字符串。