How to Convert RegEx to String and String to RegEx in JavaScript

April 08, 2022

Recently, I ran into a problem where I wanted to pass RegEx via api.

The problem is that regular expressions are not JSON serializable. So if we try to convert a object that has RegEx to JSON, the regex item will be ignored.

For example,

const config = {
  regex: /graph\.facebook\.com/i,
};
JSON.stringify(config);
// 👉 '{"denyUrls":{}}'

Solution

One way to overcome this is to convert the RegEx to string.

const config = {
  regex: '/graph.facebook.com/i',
};
JSON.stringify(config);
// 👉 '{"regex":"\/graph\.facebook\.com\/i"}'

And then convert the string back to RegEx.

We can use regex-parser package for parsing a string as regular expression under the hood.

// npm install regex-parser
const RegexParser = require('regex-parser');
const config = JSON.parse('{"regex":"/graph.facebook.com/i"}');
config.regex = RegexParser(config.regex);
// 👉 {regex: /graph.facebook.com/i}

👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2022 Nesin Technologies LLP