Home > Software design >  Extracting specific words from a string query [javaScript]
Extracting specific words from a string query [javaScript]

Time:11-21

I have a string query

const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';

I want to store the words inside "NOT" block in an array. What could be the most effective approach for this?

Expected result - ["app", "agency"]

CodePudding user response:

We can use match(), twice:

const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';
var terms = query.match(/\bNOT\s*\((.*?)\)/)[1]
                 .match(/\w /g)
                 .filter(x => x !== "OR" && x !== "AND");
console.log(terms);

CodePudding user response:

const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';
function useRegex(input) {
    let regex = /\(([a-zA-Z] ( [a-zA-Z] ) )\) NOT \(([a-zA-Z] ( [a-zA-Z] ) )\) ([A-Za-z0-9] ( [A-Za-z0-9] ) )/i;
    return input.match(regex);
}
console.log(useRegex(query)[3]);

CodePudding user response:

Step 1: Split the query before and after NOT keyword using query.split('NOT')

-> Here only data after NOT is needed so we can use, query.split('NOT')[1]

Step 2: Use regex rx.exec(res)[1] to get the value in between the paranthesis.

Step 3: Get the values before and after OR.

const query = '(travel OR explore OR vacation OR trip) NOT (app OR agency) AND flight';

const res = query.split('NOT')[1]; 
const rx = /\(([^)] )\)/;
const result = rx.exec(res)[1].split(' OR ');


console.log(result);

  • Related