0
  if (searchText.length > 3) {
   regex = new RegExp("(\\W)" + searchText, 'gi');
  }
  else {
   regex = new RegExp("(\\W)\b" + searchText + '\b', 'gi');}
  }

Obviously, I've wrapped this wrong, but if I wanted to match only whole words when the search term is 1, 2, or 3 characters, what would the correct syntax be?

e.g. "do" won't match the do in "DOne" but "heat" would match the heat in "HEATed"

key2starz
  • 747
  • 4
  • 11
  • 23
  • why would `heat` match..not able to understand your question..give us some examples – Anirudha Jan 24 '13 at 09:26
  • This regex will match partials within words: regex = new RegExp("(\\W)" + searchText, 'gi'); But if a searchText is short like "do" or "be" or "in" I don't want it matching all the words that start with "do" like "done", "door", "beyonce", "beyond", "indulge", "intrigue" etc. So only in the case of < 4 characters, I want to match using whole words \b \b -- I'm just not sure of the syntax here. – key2starz Jan 24 '13 at 09:30

1 Answers1

1

Try this..

if (searchText.length > 3) 
{
   regex = new RegExp(searchText, 'gi');
}
else 
{
   regex = new RegExp('\b' + searchText + '\b', 'gi');}
}

No need of \W before \b

Anirudha
  • 32,393
  • 7
  • 68
  • 89