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

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...