1

I am trying to test match a string if it is both singular and plural using javascript.

Because I need to use a variable I'm using RexExp like so but it's always returning true even if I use checksxcd or anything else, as long as check is there it passes.

let str = 'check'
let reg = new RegExp("(["+ str +"])(s\\b|\\b)", "g");
reg.test(check)
// Returns true

If I test this without using the str variable it works for only singluar and only plural of the word check as expected.

let reg = new RegExp(/([check])(s\b|\b)/, "g");

I'm assuming I have a syntax issue but I can't seem to find out what I'm doing wrong. Any help is appreciated.

bilcker
  • 1,120
  • 1
  • 15
  • 43
  • 1
    Using `[check]` is a character class. What do you want to match? – The fourth bird Jun 17 '22 at 15:50
  • 1
    You do not need the character class. You need a mere `let reg = new RegExp("\\b"+ str + "(?:e?s)?\\b");`. Since the `str` looks to be a natural language word consisting of letters only, you can rely on the `\b` word boundary. – Wiktor Stribiżew Jun 17 '22 at 15:50
  • Thanks for your reply, unfortunately it's still returning true on more than just check and checks. I'm trying to return true only for plural or singluar but if was checker for example to be false. – bilcker Jun 17 '22 at 16:15
  • Show your full testing code. – Wiktor Stribiżew Jun 17 '22 at 16:18
  • haha sorry, the above was pretty much it,. I'm just trying it out in codepen for the moment. https://codepen.io/bilcker/pen/VwQNZVp – bilcker Jun 17 '22 at 16:22
  • 1
    But you are using `str` in the regex and are running the check against `str` string. Of course it will always be true. Try `let reg = new RegExp("\\b"+ str + "(?:e?s)?\\b")` against `A check` string and then against `A checkl` string. Do not use `"g"` flag, it should never be used in `RegExp#test`. See [this JS demo](https://jsfiddle.net/5zsbvy2m/). – Wiktor Stribiżew Jun 17 '22 at 16:24

1 Answers1

1

You are using str in the regex and are running the check against the str string. That is why the result will always be true.

You can use

let str = 'checkl'
let reg = new RegExp("\\b"+ str + "(?:e?s)?\\b")
console.log(reg.test("A check"))  // => false
console.log(reg.test("A checkl")) // => true

Do not use g flag when using a regex in RegExp#test, that may lead to unexpected results.

Note I added an optional e before s ending, since the noun endings can be es or s.

Pattern details:

  • \b - a word boundary
  • str - the str word
  • (?:e?s)? - an optional sequence of an optional e and then s (so it is either s or es or empty string)
  • \b - a word boundary.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563