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:
![My Image](/path/to/image.jpg)
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.
However, VS Code has a find and replace feature in which you can use regex to find and replace content in your code. And you can do this within a single file or across multiple files.
The regex to target markdown images is this:
^!\[([\w\d\s']+)\]\(([\w\d\-\.\/]+)\)
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:
posts
directory.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.