DEV Community

Cover image for Making Regular Expressions Readable in JavaScript
bob.ts
bob.ts

Posted on

4

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.

They are even more difficult to reason about; 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
`;
Enter fullscreen mode Exit fullscreen mode

... rather than ...

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

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];
Enter fullscreen mode Exit fullscreen mode

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay