How to replace everything except the specified string with regex

I was browsing and from stackoverflow for this, but I had no luck.

The line I want to work with is "xbananay", where "x" and "y" can be any random combination of letters or numbers of any length. So my line might just be "qrstbananag", but it could also be "abcbanana12345".

I want to use and use the javascript replacement function to replace everything, BUT "banana". I already have some regular expression that a banana can find, but the replacement function, as expected, will replace what I am looking for when I want to find everything else. Example:

var fullString = "qrstbananag"
var strippedBanana = fullString.replace(/(?:banana)/g, ''); //returns qrstg

I also have a regex expression that ALMOST receives from me what I am looking for, but includes all the characters in the string "banana". Another example:

var fullString2 = "abcbanana12345"
var strippedBanana = fullString2.replace(/[^(?:banana)]/g, ''); //returns abbanana

How can I accomplish this using only the replace function? Thanks in advance.

+4
source share
1 answer

You can use this:

var test = 'abcbananadefbananaghi';

var result = test.replace(/(banana)|[^]/g, '$1');

console.log(result);
Run codeHide result

The point is to match the banana and return it to the result with $1. When the bananas do not match, the next character ( [^]which also matches newlines) is not written to the capture group and therefore is not included in $1.

Instead, [^]you can also use [\S\s]: the same behavior.

About classes

[^(?:banana)]

, ( [...]) , . , (?: , banana. : , : ()?:abn.

+7

All Articles