Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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 ?./

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading