javascript - matchAll:如何仅替换前 3 个匹配项超过 4 个
问题描述
此代码生成错误,我只想替换前 3 比 4 匹配
https://jsfiddle.net/9Lfj0dva/
let test = ". . . .";
const regex = /\./gm;
let matchAll = test.matchAll(regex);
console.log(Array.from(matchAll).length);
const replacements = [1, 2, 3];
test = test.replace(regex, () => replacements.next().value);
console.log(test);
解决方案
像这样的东西:
let test = ". . . .";
const regex = /\./m;
const replacements = [1, 2, 3];
replacements.forEach((replacement) => test = test.replace(regex, replacement));
console.log(test);
我从正则表达式中删除全局标志以仅替换找到的第一个匹配项,然后循环遍历替换数组。
推荐阅读
- javascript - 如何按顺序显示来自div的段落和图像?
- axios - 从函数参数向 axios http 请求发送数据
- sql - 如何根据两列最大值获取最新记录
- javascript - 由于缺少 http 模块,Electron/Angular 应用程序无法编译
- google-sheets - 使用查询从特定列中选择特定行和行范围
- visual-studio - 当sql server和wcf的主机不同时如何在visual studio中实现服务
- r - 如何在数据框的列上使用 R 的 diff 函数,条件是在不同列中具有特定值
- ios - Swift Firebase iOS didReceiveRemoteNotification 从不调用
- python - 引用框架内的标签
- kubernetes - 从 AWS EKS Autoscaler 工作程序节点中的私有 Docker 注册表中提取映像