Home > Blockchain >  JavaScript Regex: How to match terms outside of the quotation marks?
JavaScript Regex: How to match terms outside of the quotation marks?

Time:11-08

The goal is to match / and /gu and / or /gu and replace them with ' AND ' and ' OR ' but if they are inside of the quotation marks, the replacement should not have taken place.

For example, if the string is term:"cat and dog" and keyword:view or keyword:impression it should be replaced into term:"cat and dog" AND keyword:view OR keyword:impression.

I've tried this but it doesn't quite work: [^'"]*(?=(?:(['"]) (.*?\1))|([^'"]*$))((?=.* and )|(?=.* or ))

CodePudding user response:

We can try a regex replacement here, with the help of an alternation:

var input = "term:\"cat and dog\" and keyword:view or keyword:impression";
var output = input.replace(/".*?"|\w /g, (x) => x.match(/^(?:and|or)$/i) ? x.toUpperCase() : x);
console.log(output);

The trick here is to first search for "..." terms. That failing, we match any other word, one at a time. Then, in the callback replacement, we ignore doubly quoted terms, thereby ignoring and or or inside double quotes. We only make an actual replacement for and/or by uppercasing them.

  • Related