0

I want to include a regex in an array in JSON, like this:

"routes:before": {
    "./middleware/foo": {
        "enabled": false,
        "paths": [/^\/(?!css|js|img).+$/ig] // <== doesn't work, throws
    }
},

But it throws:

SyntaxError: \middleware.json: Unexpected token / in JSON at position 884

Although they say it is possible:

In addition to a literal string, route can be a path matching pattern, a regular expression, or an array including all these types.

What do I miss? How to pass a regex in an array in JSON?

Green
  • 28,742
  • 61
  • 158
  • 247
  • 2
    Possible duplicate of [Can I store RegExp and Function in JSON?](https://stackoverflow.com/questions/8328119/can-i-store-regexp-and-function-in-json) – ctwheels Dec 05 '17 at 18:47
  • So the first answer on the question from which I marked yours question a duplicate says `Store RegExp pattern as a string` and that doesn't solve your problem? `"paths": ["/^\/(?!css|js|img).+$/ig"]` – ctwheels Dec 05 '17 at 18:55
  • JSON does not know RegExp, JSON does only know `string`, `number`, `object`, `array`, `true`, `false` and `null`, as values. – t.niese Dec 05 '17 at 19:02
  • JSON can't contain RegExp. Path can be regular expression. You can check the *Route paths* section of express routing documentation (http://expressjs.com/en/guide/routing.html) to see some examples of using RexExp for path. – Alexander Dec 05 '17 at 19:18

1 Answers1

1

You would need to store it as a string, i.e. "paths": "[/^\/(?!css|js|img).+$/ig]"

Then, you can reconstruct: var re = new RegExp(paths, 'i');

JSON allows strings, booleans, numbers, objects, arrays, and null. You cannot store/transfer a regular expression unless it is as a string.

  • So you've basically copied the comments to an answer? Also your `i.e.` code is incorrect. You should provide some documentation and an excerpt from the documentation at least. – ctwheels Dec 05 '17 at 19:08
  • What is incorrect about it? And no, it was not a copy from the comments. – John-Paul Ensign Dec 05 '17 at 19:09
  • 1
    It's supposed to be an array. If the user tried to use the string you have as a regex they'd get a set of "any of the following characters": `/^(?!cs|jimg).+$` (literally) – ctwheels Dec 05 '17 at 19:11