Yesterday I was working with a JavaScript object:
javascriptlet 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:
javascriptlet 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.
javascriptlet config = { name: 'config', version: '1.0.0', rules:{ test: '/\.(js|jsx)$/' } }
Now:
javascriptlet 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:
javascriptlet 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.