首页 > 解决方案 > 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'

有人能告诉我我该怎么做吗?

标签: javascriptreplacewildcard

解决方案


尝试

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);


推荐阅读