Tips for efficiently saving a group of regular expression values in a JSON document and accessing them in JavaScript

In my Javascript file, I have an array variable that is intended to be used with the Purgecss whitelistPatterns option, specifically within the gulp-purgecss plugin:

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

I want to keep this array and other project variables in an external .json file for easy access across different files. Here's what I've tried:

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

However, I am facing errors and not achieving the desired outcome, which is to replicate the results of the purgeWLP variable inside the javascript file.

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

Answer №1

To keep them as strings without the slashes, store them that way and then convert them into 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)

For saving them, you can utilize JSON.stringify() and map each RegExp object to its source string (refer to this comment by Emanuel Vintilă):

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

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

console.log(result);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

Is it possible for me to verify the login status of an Auth0 user within my custom NextJS _app.js file?

Currently working on a NextJS application with nextjs-auth0 for authentication, which is completely new to me. I followed the documentation's suggestion and wrapped my _app.js with UserProvider, also using getInitialProps to set a global online/offlin ...

Allow iframe to be edited within jsfiddle

I have a question that I need to ask soon, but first I need an editable iframe in jsfiddle. It's working fine on my local machine, but not on jsfiddle. I believe it's because of the frames being used? On my local machine, I use: setTimeout(&apo ...

Is it possible to refresh HTML content using jQuery?

Currently, I am attempting to iterate through response data and integrate the values into the HTML of my webpage. It's crucial for me to clear any existing values in the HTML so that only the new ones are displayed, keeping it up-to-date. The structu ...

What is the best way to store text in a text area and retrieve it when the page is reloaded using jQuery or JavaScript

As a beginner in coding, I am in the process of creating a calendar on http://codepen.io/. I have included a textarea where I can input events for the month. When I click a button, the textarea data is saved to a variable. However, I am seeking a way to pe ...

What is the reason behind "readFile" consuming more memory than the actual length of the file being read?

I am facing an issue with memory consumption when handling a large number of log files in a directory containing around 300,000 files. It seems that there is a memory leak when I use the "readFile" method to read all these files. Below is an example of No ...

PHP form button refuses to coordinate

My form page was functioning well, submitting form data to an ajax request without issues. However, it suddenly stopped working and no error messages are being logged. I tried identifying the problem by reviewing recent changes made to the file, but the on ...

Failed to retrieve information from the Service for the component

My goal is to retrieve data from a service and display it in a component. Below is the code for my service: Service.ts export class PrjService { tDate: Observable<filModel[]>; prjData:Observable<filModel[]>; entityUrl; constructor(){ this ...

Retrieve specific information from a JSON file and save it in an array using Node.js/JavaScript

My goal is to extract all log details from a JSON object, but the issue is that the key for each user is constantly changing. let userJsonObject = { "user_1":{ "id":"user_1", "log":"de-data", ...

Parsing and transforming Cyrillic Unicode characters from a JSON file using C++

I have a JSON file containing the following data (as an example): { "excel_filepath": "excel_file.xlsx", "line_length": 5.0, "record_frequency": 2.5, "report_file_name": "\u041f&bs ...

Error message occurring in React datatable: Unable to read property 'map' of undefined

Encountering an issue with the map function. generateRows: function() { var cols = this.props.cols, // [{key, label}] data = this.props.data; Getting an error in retrieving data as it returns undefined value. return data.map(function(i ...

Bootstrap carousel button that tracks the number of clicks

Unfortunately, I am facing a challenging issue with creating a click counter for the Bootstrap carousel button. The problem seems to be related to the span element for the previous and next icons. The button counter is not registering clicks on the respec ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...

The location of the THREE.Group object is consistently set at the origin (0, 0, 0) and errors may arise when attempting to accurately determine its position

In my Three.js project, I am utilizing a THREE.Group to manage selected dominoes within the scene. However, I am facing an issue where the reported position of the THREE.Group remains constant at (0, 0, 0) despite adding or removing objects to it. Addition ...

Javascript adds a comma after every postback event

This particular JavaScript code I am incorporating helps in expanding and collapsing nested grid views. <script type="text/javascript"> $("[src*=plus]").live("click", function () { $(this).closest("tr").after("<tr><td></td ...

Unable to Pass POST Parameters Through Volley Request

I am facing an issue with the code implemented on my Android client: int method = Request.Method.POST; JSONObject params = new JSONObject(); try { params.put("data", userJson); } catch (JSONException e) { LogSystem.e(tag, ...

The result of UserDefaults in Swift is null

Attempting to master the art of creating a todolist; I'm working with two view controllers, one for storing and one for displaying in a table view. My table is returning nil; where could I be making a mistake? Storage view: var toDoStorage = Use ...

What is the reason that PHP has the ability to set Cookies but Local Storage does not?

Let's take a step back to the era of cookies, not too far back since they are considered old but still quite relevant. PHP allows you to set and read them even though they are a client-side technology; however, JavaScript can also be used completely o ...

Generating aggregated statistics from JSON logs using Apache Spark

Recently delving into the world of Apache Spark, I've encountered a task involving the conversion of a JSON log into a flattened set of metrics. Essentially, transforming it into a simple CSV format. For instance: "orderId":1, "orderData": { ...

Ways to identify the moment when a user enters an "@" symbol in an input field

I am looking to enable a disabled button when a user enters the "@" symbol. const isDisabled = () =>{ const value = getValues('email') if ... } I require the if statement to evaluate to true if the input contains the "@" symbol, and ...