Making Regular Expressions Readable in JavaScript

Making Regular Expressions Readable in JavaScript

Reggie-Docs

"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];

Conclusion

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.