[英]Replace part of string that doesn't match regex
我正在尝试使用JavaScript替换与正则表达式模式不匹配的字符串部分。 这在功能上等同于在GNU grep中使用-v
标志来反转结果。 这是一个例子:
// I want to replace all characters that don't match "fore"
// in "aforementioned" with "*"
'aforementioned'.replace(new RegExp(pattern, 'i'), function(match){
//generates a string of '*' that is the length of match
return new Array(match.length).join('*');
});
我正在寻找pattern
的正则表达式。 这就像(fore)
的相反。 我进行了搜索,但未能实现任何相关问题的答案来满足我的需求。 无论如何,这是一个列表,也许它将为我们指明正确的方向:
如果我对您的理解正确,那么这应该是一种可能的解决方案:
'aforementioned'.replace(new RegExp(pattern + '|.', 'gi'), function(c) {
return c === pattern ? c : '*';
});
>> "*fore*********"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.