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

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

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?

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.

Full-Stack Developer, Teacher, Maker, and general Things-Doer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store