-2

Here is the my string

var string = 'Title:(India OR America) OR Keyword:(Education)';

After splitting with "OR" it is showing

["Title:(India", "America)", "Keyword:(Education)"]

But what I need is the below one.

["Title:(India OR America)", "Keyword:(Education)"]

Could anyone please help on how to split the string to get the required result.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

5

To achieve this you'll need to use a negative lookahead to only find the OR string where it's not contained in parentheses. Try this:

var input = 'Title:(India OR America) OR Keyword:(Education)';
var output = input.split(/(?!\(.*)\s?OR\s?(?![^(]*?\))/g);

console.log(output);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Hi Rory. Yes it worked well. But in some cases I need to split both with AND or OR var string4 = 'Title:(India OR America) OR Sector:(Education) AND Sector:(Health)'; could you please update the above regex to split with both AND or OR – user9449539 Jan 29 '20 at 08:47