How to stringify an object when there is a regular expression

Yesterday I was working with a JavaScript object:

javascript
let config = {
    
    name: 'config',
    version: '1.0.0',
    rules:{
        test: /\.(js|jsx)$/
    } 
    
}

The value of test is a regular expression (RegEx). As I needed to write the object into a new file, I was obligued to stringify it:

javascript
let string = JSON.stringify(config);

// "{"name":"config","version":"1.0.0","rules":{"test":{}}}"

Look how JSON.stringify() returns an empty object {} in the test property. This is not desired, since I wanted to keep the regular expression in that field.

The problem is that JSON.stringify() doesn't recognize regular expressions, so I took a different approach; I placed quotation marks around the regular expression.

javascript
let config = {
    
    name: 'config',
    version: '1.0.0',
    rules:{
        test: '/\.(js|jsx)$/'
    } 
    
}

Now:

javascript
let string = JSON.stringify(config);

// "{"name":"config","version":"1.0.0","rules":{"test":"/.(js|jsx)$/"}}"

Now the regular expression appears. We are close, but this isn't desired either. We want to get rid off the quotation marks around the regular expression:

javascript
let stringNoQuotations = string.replace(`"/.(js|jsx)$/"`, `/.(js|jsx)$/`);

// "{"name":"config","version":"1.0.0","rules":{"test":/.(js|jsx)$/}}"

Et voilà.

So the final solution was:

javascript
// Defining the object
let config = {
    
    name: 'config',
    version: '1.0.0',
    rules:{
        test: /\.(js|jsx)$/
    } 
    
}

// Transforming object into string
let string = JSON.stringify(config);

// Deleting quotation marks from the string
let stringNoQuotations = string.replace(`"/.(js|jsx)$/"`, `/.(js|jsx)$/`);

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.