I am attempting to replace parts of a string that don't match a regular expression pattern using JavaScript. This is functionally equivalent to using the -v flag in a GNU grep to invert results. Here is an example:
-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('*'); });
I am looking for a regex for pattern. This would be something like the opposite of (fore). I've searched around but haven't been able to implement any related question's answers to fit my needs. Here is a list anyway, maybe it will point us in the right direction:
pattern
(fore)
If I understand you correctly, this should be one possible solution:
'aforementioned'.replace(new RegExp(pattern + '|.', 'gi'), function(c) { return c === pattern ? c : '*'; }); >> "*fore*********"
1.4m articles
1.4m replys
5 comments
57.0k users