OMBD#19: A New Addition to Your Regex Toolbelt, Meet the Lazy Quantifier

Save refactor time with one character — Regular expressions on JavaScript or any other language made easier

Jon Portella
2 min readMar 19, 2021

Welcome to issue #19 of One Minute Better Developer, where you become a more successful software developer by reading short nuggets of knowledge, one minute at a time.

⏮️ 🔛 ⏭️

Art by my buddy Loor Nicolas

THE PROBLEM

We have a block of HTML code, including a set of images.

All of them have an alt tag, but we want to add a full stop to every tag, to make screen readers pause for a bit when reading the tag.

A set of images with alt tags without full stops.

We could just capture everything between “”. However, that would also target the src tag of the first image, since, by default, RegEx quantifiers are greedy, so we are capturing until the last occurrence of in the line.

We wrongly target the src tag of the first image.

How can we do it?

A SOLUTION

We are going to use a RegEx Lazy (or Non-Greedy) Quantifier to match only the alt tags and add them back with a full stop.

We only need to add a ? after the quantifier.

Lazy Quantifier allows us to only target the alt tag.

Here’s a demo on CodePen. Also here’s a demo on RegExr.

--

--

Jon Portella
Jon Portella

Written by Jon Portella

Software Engineer @ Pinterest - Teacher, maker, and general things do-er. - https://www.linkedin.com/in/jonportella/ - Toronto, Canada

No responses yet