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

130
Visualizações
Regexpr with a string

I have to get the result from this regular expression; the regular expression is a string in a variable:

const dataFileUrlRegExpr = new RegExp(            
    "\\/home-affairs\\/document\\/download\\/([\\\\w-]{1,})_en?filename=visa_statistics_for_consulates_20[0-9]{2}.xlsx"
);
href = '/home-affairs/document/download/75ecba81-12db-42b0-a628-795d3292c680_en?filename=visa_statistics_for_consulates_2020.xlsx'

xlslHrefRegExpResult = dataFileUrlRegExpr.exec(xlslHref);

but the xlslHrefRegExpResult variable is null.

If I use:

const dataFileUrlRegExpr = new RegExp(
    /\/home-affairs\/document\/download\/([\w-]{1,})_en\?filename=visa_statistics_for_consulates_20[0-9]{2}.xlsx/g
);

without the string variable containing the expression, the result is achieved.
Where is the error using a string to build the regexp?

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

0

  • Don't escape / at all, because it's nothing special inside a non-literal regex.
  • Do escape the backslash in \w, but only once.
  • Do escape the ? and the backslash itself.
  • Do escape the . and the backslash itself.
dataFileUrlRegExpr = new RegExp(            
    "/home-affairs/document/download/([\\w-]{1,})_en\\?filename=visa_statistics_for_consulates_20[0-9]{2}\\.xlsx"
);

In short: write your regexp as normal, but double every backslash inside it so that it doesn't get interpreted as an escape character inside the string.

about 4 years ago · Juan Pablo Isaza Relatório

0

The correct code should be:

const dataFileUrlRegExpr = new RegExp(            
    "\\/home-affairs\\/document\\/download\\/([\\w-]{1,})_en\\?filename=visa_statistics_for_consulates_20[0-9]{2}.xlsx", 'g'
);
href = '/home-affairs/document/download/75ecba81-12db-42b0-a628-795d3292c680_en?filename=visa_statistics_for_consulates_2020.xlsx'

xlslHrefRegExpResult = dataFileUrlRegExpr.exec(href);
console.log(xlslHrefRegExpResult)

You had too many backslashes in [\\\\w-], and you were missing the backslashes before ?./

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