How can I remove all occurrences of a certain value unless it is part of the quoted text?


Using regular expressions, I want to remove all instances of a certain value unless the value is part of quoted text when it is found.

For example, if I want to remove the word book unless it is found in quotes, and I have the following text:

telephone book computer "i read a book" keyboard book

How can I use regular expressions to make it appear as:

telephone computer "i read a book" keyboard

Is this possible with WebKit JavaScript regex using string.replace?

You can do it with help of a callback (demo):

result = str.replace(/\bbook\b\s*|("[^"]*")/g, function(m, quotes){ return quotes ? quotes: '' });

Or with help of a lookahead trick like (demo):

result = str.replace(/\bbook\b\s*(?=[^"]*(?:"[^"]*"[^"]*)*$)/g, '');

Last one only only works if quotes are always closed, and may not be efficient for long strings.