0

I have a simple list such as:

Health, Health Care, Health Options

My search term is the word "Health". When searching for "Health" I do not want to match "Health Care" and "Health Options" because technically those are different items on the list.

After reading Regex documentation I figured I was supposed to use a lookbehind to check for preceding text. But from what I understand those options are not present in the JS regex.

In summary I need to match a specific value in a group, where the group is a term before/after a comma.

gdaniel
  • 1,307
  • 2
  • 10
  • 17
  • 1
    Why can't you [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) the list on commas and then [search](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) the term in the array. – abhishekkannojia Mar 30 '17 at 18:26
  • I agree, you should split this list which is presumably a string then search the resulting array for the terms you want – jakeehoffmann Mar 30 '17 at 18:28
  • It would also be helpful to post some example code with actual input and expected output :) – Kenan Banks Mar 30 '17 at 18:29
  • I can't split the list. I get a value, and I need to match it again the list with a regex. It's part of another script. – gdaniel Mar 30 '17 at 21:32

1 Answers1

0

If you really need to use regex, the following would work:

var str = "Cat Health, Health, Health Care, Health Options",
    reg = /(?:[^,], )*(Health)(?:, [^,])*/;

alert(str.match(reg)[1]);
// -> Health

Regex Explanation:

  1. Non-comma stuff followed by a comma and a space -- repeated 0-n times.
  2. "Health"
  3. Comma, space, non-comma stuff -- repeated 0-n times

Note that there is no lookbehind in Javascript Regex, see:
Positive look behind in JavaScript regular expression

To do it programmatically as suggested in comments (assuming the list items are always separated by a comma then a space):

var str = "Cat Health, Health, Health Care, Health Options"
var list = str.split(/, /);
var a = list.indexOf("Health");
// a = -1 if not found, otherwise contains the index of "Health" in the list 
Community
  • 1
  • 1
jakeehoffmann
  • 1,364
  • 14
  • 22
  • Wouldn't your example fail to match the first item in "Health, Health care"? Because it doesn't start with a comma or a space? – gdaniel Mar 30 '17 at 21:33
  • But based on your responsive I think I can do this -> /,? ?(health),/ – gdaniel Mar 30 '17 at 21:49