Make a bulk conversion of markdown images to HTML strings using a regex find and replace with VS Code.
There are times when the syntax for an image in markdown may not be enough to generate the HTML you desire.
The cases for this can vary significantly, but are often born from wanting additional HTML attributes that your markdown processor does not support and that may not make sense to manually build into the processor.
Consider the case of adding a class to your image. While there are markdown processors out there that support classes, let’s assume you’re not using one of these. And you want to add a
border class to your image.
Your markdown code looks something like this:
But what you want is this:
<img src="/path/to/image.jpg" alt="My Image" class="border" />
Making changes like this manually is fine when there are a select few cases. But when you want to make a change like this on a broader scale, it can quickly become a tiresome process.
The regex to target markdown images is this:
And that will be replaced with this string:
<img src="$2" alt="$1" />
The reason this works is because the parentheses in the regex code become groups that can be used when replacing the content. The first group (
$1) is the alt text, which is the content inside the square brackets. And the second group (
$2) is the path to the image, which is found inside the parentheses in the markdown syntax.
This is what it looks like:
Here is a brief explanations about the annotations:
When you’re ready to make the change, you can click the icon below #5 (to the right of the replace value) and confirm that you wish to make the changes.
And because you’re making changes to local files, if you’re tracking changes with Git, you get a second chance to look to see everything was right before committing.