javascript - JavaScript 如何使用通配符替换
问题描述
我有一个字符串,其中可能包含随机字符。我想用通配符支持替换一个部分的所有实例。例子:
var input = 'abcdef acbdef acdbef';
input = coolFunction(input, 'a*b', '_');
// I want to replace every charachter between an a and the next closest b with _'s
//Output should be '__cdef ___def ____ef'
有人能告诉我我该怎么做吗?
解决方案
尝试
let input = 'abcdef acbdef acdbef';
let wild = 'a*b';
let re = new RegExp(wild.replace(/\?/,'.').replace(/\*/,'.*?'),'g');
let output = input.replace(re, c => '_'.repeat(c.length));
console.log(output);
推荐阅读
- html - HTML 脚本标签中的 Golang JSON
- windows - 使用 PowerShell 更改音频输出设备
- shell - 如何将shell变量传递给ansible playbook命令
- java - Java - 通过另一个数组安装一个数组
- sql - Postgresql 中 AS ' ' 的替代方案是什么?
- ios - 如何更改适用于 M1 Mac 的 Flutter 应用程序的名称?
- python - 熊猫数据框从宽到长
- c - 如何确定当前阻塞了哪个 UMS 线程?
- cypress - 不能将 cypress 与需要身份验证的代理一起使用
- azure-devops - 是否可以在 azure devops 中禁用发布管道的手动触发