-1

I currently have a regex that looks like:

const ignoreRegex = new RegExp(/^\/(?!fonts|static).*$/)

However, I also have a dynamic array of strings like "test" which need to be ignored too. I need to somehow map through this array and add each string to the regex, such that:

  const ignoreRegex = new RegExp(/^\/(?!fonts|static + ignoreRoutes.map(x => `|${x}`) + ).*$/)

How do I do this?

j_d
  • 2,818
  • 9
  • 50
  • 91

2 Answers2

3

You can omit the / / surrounding your regular expression and use a string in the RegExp constructor.

See the code below.

const ignoreFolders = ["fonts", "static"];
const ignoreRoutes = ["route1", "route2"];
const ignore = ignoreFolders.concat(ignoreRoutes);

const ignoreRegex = new RegExp(`^\/(?!${ignore.join("|")}).*$`);

console.log(ignoreRegex);

If you have any regex special characters in your string, they will be escaped automatically.

Vivek
  • 2,665
  • 1
  • 18
  • 20
  • It seems to be adding a `\/` before each string in my dev environment. Maybe because of babel transpilation? Output looks like: `/^\/(?!\/fonts|\/static).*$/` – j_d Dec 27 '18 at 08:48
  • Probably you are trying to ignore ```/fonts``` rather than ```fonts```. In regular expression, ```/``` has a special meaning. So ```/``` has to be escaped using ```\/```. – Vivek Dec 27 '18 at 08:52
  • If you don't want ```\/```, make sure to remove all ```/``` that appears before the strings in ```ignoreRoutes``` array. – Vivek Dec 27 '18 at 08:53
0
const ignoreRoutes = ["fonts","static","aaa","bbb","ccc"];
const ignoreRegex = new RegExp(`^\\/(?!${ignoreRoutes.join("|")}).*$`);
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Vadim Hulevich
  • 1,803
  • 8
  • 17
  • It seems to be adding a \/ before each string in my dev environment. Maybe because of babel transpilation? Output looks like: /^\/(?!\/fonts|\/static).*$/ – j_d Dec 27 '18 at 08:51
  • try "+". new RegExp('^\\/(?!'+(ignoreRoutes.join("|"))+').*$'); – Vadim Hulevich Dec 27 '18 at 08:55