0

I have the following statement:

if (new RegExp("\\b" + product.toLowerCase() + "\\b").test(cellVal.toLowerCase())) {
    console.log(product.toLowerCase() + " : " + cellVal.toLowerCase());
}

I'm having an issue with products that are similar. I have the following products that are causing an issue:

  1. tpd
  2. tpd - activity

What I'm finding is that the test statement is passing as true when tpd or tpd - activity is passed in and tested against each other.

What I would like is if tpd is found as a whole word then the test should pass. If tpd - activity is found then that should pass. But what is happening is that tpd is also picking up a match in tpd - activity. I thought the \\b would account for this scenario.

product is coming from a database list and both products are valid. cellVal is the text from an HTML table.

Any ideas?

webdad3
  • 8,893
  • 30
  • 121
  • 223
  • Is there any extra text in `cellVal` or is it only going to be `tpd` or `tpd - activity` (well, among the other values). – VLAZ May 11 '18 at 19:01
  • @vlaz - there is some variation in the cellVal (especially in the tpd - activity, I've seen it where it has tpd - activity base as well) - however if it finds tpd -activity then it needs to match on that. – webdad3 May 11 '18 at 19:02
  • 2
    Replace both `\\b` tokens with `^` and `$` respectively: `new RegExp("^" + product.toLowerCase() + "$")` – revo May 11 '18 at 19:02
  • You're regex just test if the word `product` is present in the `cellValue` and `"tpd - activity"` contains `"tpd"`. `\b` just checks for a word boundary (space, punctuation, etc.) – Titus May 11 '18 at 19:03
  • @revo - That looks like that cleared up my issue. If you want to add your answer I will accept it. – webdad3 May 11 '18 at 19:07
  • 2
    I hate to be the bearer of bad news, but if adding `^$` fixes your problem, then you don't need regex at all. A simple string compare is all you need: `if ( product.toLowerCase() == cellVal.toLowerCase() )` –  May 11 '18 at 19:38

2 Answers2

1

Using word boundaries you can assert boundaries around words not an entire input string. For matching against whole string you need ^ (caret - beginning of input string) and $ (dollar - end of input string) anchors:

new RegExp("^" + product.toLowerCase() + "$")
revo
  • 47,783
  • 14
  • 74
  • 117
0

Sort the products backwards after length:

const products = ["tpd - activity", "tpd"];

(If you actually need to sort them programmatically):

products.sort((a, b) => b.length - a.length);

Then get the first included:

const result = products.find(p => cellVal.toLowerCase().includes(p));

console.log(result);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151