skip to Main Content

i have multiple markdown files that contain images without alt that look like:

# my file

![](./filename-1.png)

# this is an example image

![](./this-is-a-an-example-image.png)

i want to replace them with alt from the filename but without the .png extension & without ./ & replacing hyphens (- ) with empty spaces.

so the above markdown would look like:

# my file

![filename 1](./filename-1.png)

# this is an example image

![this is an example image](./this-is-an-example-image.png)

i can’t do this manually as i have 100+ images so would love to automate this with a regex using vscode’s find & replace.

i had previously removed alt but want it back now. i didn’t version control it so can’t go back either.

how do i do it?

2

Answers


  1. Chosen as BEST ANSWER

    this is the demo on regex101 to find the group between ./ & .pnghttps://regex101.com/r/gMgc6r/1

    important: i enabled the search in each file, not the sidebar & ticked the .* button that says use regular expression

    then i typed the following:

    find: ![](./(.*).png)
    replace: ![$1](./$1.png)
    

    this converts:

    ![](./a-filename.png)
    

    to

    ![a-filename](./a-filename.png)
    

    this finds the string between each bracket [ & ]https://regex101.com/r/Ke89CK/1 but i couldn't figure out how to use it in vscode.

    i have to convert [a-filename] by replacing - with empty spaces.

    find: ?
    replace: ?
    

  2. Here is how to do it with an extension, Find and Transform, that can run two find and replaces in a row. Install the extension and then make this keybinding (in your keybindings.json):

    {
      "key": "alt+m",
      "command": "findInCurrentFile",
      "args": {
        "find": [
          "(!\[\])\((\.\/)?(.*)(\.(png|jpg|gif)\))",
          "(?<=!\[.*)(-)(?=.*\])"
        ],
        "replace": ["![$3]($2$3$4", " "],
        "isRegex": true,
        "postCommands": "cancelSelection"
      }
    }
    

    I made it to handle other image formats which you may not need.

    The first find and replace just moves the filename (minus the leading . and trailing .png) into the ![].

    The second find matches just the - in that ![asdasd-asdasd-asdasd] and replaces those - with " " i.e., one space.

    add markdown image alt text

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search