Regular Expression Match Groups

By  on  

Regular expressions are incredibly powerful but can be difficult to maintain. They're a skill you learn on the job and, when the suits walk by, make you look incredibly smart if you have a few up on your screen. How can we solve the maintainability problem? With a match groups, as Addy Osmani enlightened me about last week:

https://twitter.com/addyosmani/status/1386031624232456194

Look at the ?<descriptor> pattern, with the descriptor being a meaningful name that you want to give to a give group. With the group usage, you can more intelligently handle match results:

const re = /(?\d{4})-(?\d{2})-(?\d{2})/;
const result = re.exec('2021-04-26');

// Deconstructing from result.groups
const { year, month, day } = result.groups;

// Using array syntax
const [, year, month, day] = result;

The only real downside of using this strategy is that most developers probably don't know about it. You could also complain that it makes the regular expression longer. In the end, however, maintainability rules the day, and I love that Addy shared this tip with us!

Recent Features

  • By
    Interview with a Pornhub Web Developer

    Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    CSS Scoped Styles

    There are plenty of awesome new attributes we've gotten during the HTML5 revolution:  placeholder, download, hidden, and more.  Each of these attributes provides us a different level of control over an element on the page, but there's a new element attribute that allows...

  • By
    MooTools ASCII Art

    I didn't realize that I truly was a nerd until I could admit to myself that ASCII art was better than the pieces Picasso, Monet, or Van Gogh could create.  ASCII art is unmatched in its beauty, simplicity, and ... OK, well, I'm being ridiculous;  ASCII...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!