Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...