Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
Correct RegExp Syntax using a Variable

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda