Making Regular Expressions Readable in JavaScript


"My first foray into Open Source development."

Now, this is not the first time I've contributed to open-source software. It is the first time I have submitted my own project to npmjs.

The Project: Reggie Docs

Regular Expressions are complicated to write.

It's even more difficult to reason about them; especially if you have to read someone else's code.

About a year ago, I wrote an article about an experiment I was working with (see it HERE). I've actually used this pattern several times since writing the article and working through the code.

Then, someone said, "this should be an open-source library."

And ... something in my brain clicked.

And ... I started reworking the codebase I had into something more functional.

The Open-Source Project

The project is here: reggie-docs.

This project will allow a developer to use a Template Literal to build a regex, with comments to make it more readable.

const code0001 = `
  /* Matches text avoiding additional spaces
  ^       // Beginning of line
  [\\s]*  // Zero or more whitespace
  (.*?)   // Any characters, zero to unlimited,
          //   lazy (as few times as possible, expanding as needed)
  [\\s]*  // Zero or more whitespace
  $       // End of line

... rather than ...

const code0001regex = /^[\s]*(.*?)[\s]*$/;

Here's a pattern for use of the code0001 above ...

const Reggie = require('reggie-docs');
const reggie = new Reggie();

let results = {};

const patternCheck0001 = '  Test Spaces Before and After   ';

results.code0001 = reggie.create(code0001);
const code0001Exp = reggie.generate(code0001);
results.code0001Test = code0001Exp.exec(patternCheck0001)[1];


The whole concept of this project is to make Regular Expressions easier to understand and reason about. In doing this, the process should be simple and easy to work with.

Comments (3)

Edidiong Asikpo's photo

Oh wow, this open source project might just be what will solve the problem almost every developer has with Regex. I am so going to try using it.

Bob Fornal's photo

That's exactly what I was hoping to hear.

I had a project with a lot of Regex and struggled with a way to write it so that someone else taking over the project could read and understand what I was trying to do.

If you've got any suggestions for improvements, please let me know.

Edidiong Asikpo's photo

Bob Fornal I can totally relate. I will try out the project and let you know if I have any feedback.