1

I have the following array variable in a Javascript file, meant to be passed to Purgecss for its whitelistPatterns option (please note that I'm specifically using it from the gulp-purgecss plugin):

var purgeWLP = [
    /^carousel-item.*/,    
    /collapsing/,           
    /show/,                
];

Now I want to store this and other project variables in an external .json file, meant to be accessed from various places and files; I've tried with the following code:

{
    "wlp": [
        "/^carousel-item.*/",
        "/collapsing/",
        "/show/"
    ]
}

But I'm experiencing errors and not getting what I expect, namely the same exact results as with the purgeWLP variable in the javascript file.

How can I correctly store an array of regex values inside a .json file and retrieve it from Javascript?

Sekhemty
  • 1,222
  • 2
  • 13
  • 33

1 Answers1

5

Store them as strings without the slashes, and convert them back to RegExp objects after parsing the JSON string:

const json = `{
    "wlp": [
        "^carousel-item.*",
        "collapsing",
        "show"
    ]
}`

const wlp = JSON.parse(json).wlp // or const wlp = require('./project.json').wlp on nodejs
  .map(str => new RegExp(str))

console.log(wlp)

And to save them you can use JSON.stringify() and map each RegExp object to its source string (see this comment by Emanuel Vintilă):

var purgeWLP = [
    /^carousel-item.*/,    
    /collapsing/,           
    /show/,                
];

var result = JSON.stringify(purgeWLP.map(re => re.source));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    And if you want to save them, `JSON.stringify(wlp.map(re => re.source))` – Emanuel Vintilă Jan 05 '20 at 20:42
  • Word of caution, make sure backslashes are escaped correctly. `new RegExp("\\s")` not `new RegExp("\s")`. – ggorlen Jan 05 '20 at 20:46
  • Good point @ggorlen, and this is a nice answer that explains how to it - https://stackoverflow.com/a/3561711/5157454. btw - strings from `Regex.source` are escaped. – Ori Drori Jan 05 '20 at 20:51
  • Thank you, this works if I store the JSON object inside the Javascript file, like in your example; but if i try to get the array from an actual external `.json` (imported with `const project = require('./config/project.json');`, I get an Unexpected token error. – Sekhemty Jan 05 '20 at 21:19
  • Use a JSON validator like [JSONLint](https://jsonlint.com/) to find the error in your file. – Ori Drori Jan 05 '20 at 22:09
  • I solved by using `const wlp = require('./config/project.json').wlp` instead of `const wlp = JSON.parse(json).wlp` as you suggested. It now works fine. – Sekhemty Jan 06 '20 at 00:10
  • I missed that you are working on nodejs (gulp). Requiring a JSON file parses it automatically. – Ori Drori Jan 06 '20 at 07:13