javascript - String.replaceAll 在 JS 的两个参数中使用正则表达式
问题描述
我需要用子字符串的修改版本替换子字符串的所有实例,我可以执行以下操作:
const regex = /[0-9]{4}[A-Z]{3}/g; // format: 0000ABC
myString = myString.replaceAll(regex, regex + " I'm modified");
抽象例子
如果 myString 是
5000ABC、250XYZ、GEN3000
我想修改某些 4 位 - 3 个字母的模式,我的预期输出是
5000ABC我改装,250XYZ,1000DEF我改装,GEN3000
解决方案
我目前的解决方法是
const regex = /[0-9]{4}[A-Z]{3}/g;
var matches = myString.match(regex);
if (matches && matches.length > 0) {
for (var match of matches) {
var modified = match + "I'm modified";
myString = myString.replaceAll(match, modified)
}
}
推荐阅读
- javascript - 为什么 D3 在使用 data().enter() 时不在所选元素内插入元素?
- vb.net-2010 - 结合数字(小键盘)和按键功能
- java - 控制器未填充复合 PK 对象
- python - 从折线图中提取 (x,y) 值
- swift - 如何在 Swift 中使用结果
- javascript - 如何更改在 React 中作为状态传递的对象内的数组项值?
- css - 我的评分和评论部分没有响应并且在小屏幕上显示很糟糕
- r - 以 data.table 方式合并 2 个 data.tables 与多于一列
- spring-cloud-dataflow - 在 Spring Cloud Data Flow 服务器中启动 SpringBatch 应用程序,其中 springboot 微服务在单独的独立服务器中运行
- python - 是否可以根据 python 中的另一个键搜索 json 对象键?