语法
stringObject.replace(regexp/substr,replacement)
| 参数 | 描述 |
|---|---|
| regexp/substr | 必需。规定子字符串或要替换的模式的 RegExp 对象。 |
| replacement | 必需。一个字符串值。规定了替换文本或生成替换文本的函数。 |
第一种情况
- 传入字符串。
第二种情况
- 传入回调函数:匹配到几次结果就会执行几次回调,参数是匹配到的值。 示例:
/**
* 规则:
* 1. str是一串数字,把所有的数字n替换成数组第n项的name;
* 2. 如果匹配不存在这项,返回原来的数字n;
* */
const arr = [
{ name: "第一个" },
{ name: "第二个" },
{ name: "第三个" },
{ name: "第四个" },
{ name: "第五个" },
];
let str = "2354618";
const result = str.replace(/\d/g, val => {
const target = arr[val -1];
return target ? target.name : val;
})
console.log(result); // 第二个第三个第五个第四个6第一个8