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.
⏮️ 🔛 ⏭️
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.
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.
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.
Here’s a demo on CodePen. Also here’s a demo on RegExr.