简体   繁体   中英

Replace part of string that doesn't match regex

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:

// 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:

If I understand you correctly, this should be one possible solution:

'aforementioned'.replace(new RegExp(pattern + '|.', 'gi'), function(c) {
    return c === pattern ? c : '*';
});

>> "*fore*********"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM