Visual Studio Code: How to automate a simple regex-find and replace?

This extension does the job:

https://marketplace.visualstudio.com/items?itemName=joekon.ssmacro#overview

It seems like the regex adheres to:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Example

Create a file regex.json:

[{
    "command": "ssmacro.replace",
    "args": {
        "info": "strip out EOL whitespace",
        "find": "\\s+$",
        "replace": "",
        "all": true,
        "reg": true,
        "flag": "gm"
    }
}]

"info" is just a reminder, doesn't do anything.

Set a shortcut in keybindings.json:

"key": "ctrl+9",
"command": "ssmacro.macro", "args": {"path": "C:\\...\\regex.json"}

You can batch multiple commands together [{...},{...}] which is useful for applying a whole set of regex operations in one go.


As of today, it seems it's still not possible without an extension. Here are 2 other extensions than the one proposed in the accepted answer (both are also open-source):

● Batch Replacer (but it doesn't work on the documents open in the editor : "you must have a folder open for editing and all files in it will be updated."*)

● Replace Rules: you simply add some rules in your settings.json (open the palette with F1 or ctrl+shift+p and select Preferences: open settings (JSON)).

"replacerules.rules": {
    "Remove trailing and leading whitespace": {
        "find": "^\\s*(.*)\\s*$",
        "replace": "$1"
    },
    "Remove blank lines": {
        "find": "^\\n",
        "replace": "",
        "languages": [
            "typescript"
        ]
    }
}