【问题标题】:JavaScript how to replace using wildcardsJavaScript 如何使用通配符替换
【发布时间】:2019-08-21 16:27:04
【问题描述】:

我有一个字符串,其中可能包含随机字符。我想用通配符支持替换一个部分的所有实例。示例:

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'

谁能告诉我该怎么做?

【问题讨论】:

标签: javascript replace wildcard


【解决方案1】:

试试

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

【讨论】:

  • 检查您的输出,然后检查请求的输出。他们希望他们替换的每个字母都有一个下划线。所以第二个例子中有三个下划线,第三个例子中有四个。
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2017-02-23
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多