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

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.

--

--

--

Full-Stack Developer, Teacher, Maker, and general Things-Doer. https://www.linkedin.com/in/jonportella/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

50+ Kafka Interview Questions and Answers (The Ultimate Guide) In 2022

50+ Kafka Interview Questions and Answers (The Ultimate Guide) In 2022

Fragmented Communication Destroys Teams’ Performance

AppGallery Connect — Analytics

Mendix Security Improvement: RedHat’s Docker Buildpack

PHP Design Patterns — Prototype

How to Program a Two Button Step Menu for Arduino Projects

Unity Slot Machine Programming

Leveraging AWS Lambda for Image Compression at scale

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
Jon Portella

Jon Portella

Full-Stack Developer, Teacher, Maker, and general Things-Doer. https://www.linkedin.com/in/jonportella/

More from Medium

How to Develop JavaScript Skills with Practical Approach and Real life Projects

How to print the number of years and months and the total number of days between dates without…

How to get better at building JavaScript projects as a beginner developer

The Struggles/Regrets Of A Self Taught Software Developer