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
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    Create a Sheen Logo Effect with CSS

    I was inspired when I first saw Addy Osmani's original ShineTime blog post.  The hover sheen effect is simple but awesome.  When I started my blog redesign, I really wanted to use a sheen effect with my logo.  Using two HTML elements and...

Incredible Demos

  • By
    Add Styles to Console Statements

    I was recently checking out Google Plus because they implement some awesome effects.  I opened the console and same the following message: WARNING! Using this console may allow attackers to impersonate you and steal your information using an attack called Self-XSS. Do not enter or paste code that you...

  • By
    Create a Spinning, Zooming Effect with CSS3

    In case you weren't aware, CSS animations are awesome.  They're smooth, less taxing than JavaScript, and are the future of node animation within browsers.  Dojo's mobile solution, dojox.mobile, uses CSS animations instead of JavaScript to lighten the application's JavaScript footprint.  One of my favorite effects...

Discussion

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