Reputation: 1821
I would like to match the following term in JavaScript using regex.
String = 'abc AND def AND igk AND lmn'
Terms to match:
the word before and after first AND
.
For example in the above string the match part will be : abc AND def
.
I want to do it in JavaScript. So I will call
string.match(/regex to use/)
and assign it to a var.
Any suggestions please.
EDIT:
the string can be of form like:
string = 'AND abc';
string = 'abc AND';
string = 'abc def AND igk lmn';
string = 'abc def AND';
string = 'AND igk lmn';
Appreciate your help in this regard.
Upvotes: 0
Views: 139
Reputation: 8558
You can try this regex:
/(\w+\s+AND\s+\w+)/
EDIT (after having read your last update): if left and right terms are optional, use the following regex instead:
/(?: (\w+) \s+)? AND (?: \s+ (\w+))?/x
Upvotes: 3
Reputation: 16063
A slight improvement on Igor's version :
var m = str.match (/(\w+)\s+AND\s+(\w+)/);
// word before AND in m[1], word after AND in m[2]
Automagically extracts the two words.
Upvotes: 1