DEV Community

Cover image for advanced find replace in vscode using regex
Johannes Dato
Johannes Dato

Posted on

advanced find replace in vscode using regex

tldr;

The $ operator lets you select all regex results from 0-n in the replace section (n = #regex results).

Image description

Important hint: If your result doesn't show up using $1, try $0 first.

A little tale how I stumbled upon it

I wanted to replace CSS values across dozens of files. I needed to replace width: 200px; with width: px(200);, thus preserve part of the search result and wrap it with some other text. Therefore I needed a regex replace that didn't strip too much of the result that I wanted.

vscode supports a lot more find replace than I knew.

What I had: style.scss

@function px($v) {
  @return 1px * $v;
}

body {
  width: 200px;

  .some-class {
    width: 15.55px;
  }
}
Enter fullscreen mode Exit fullscreen mode

What I wanted: style.scss

@function px($v) {
  @return 1px * $v;
}

body {
  width: px(200);

  .some-class {
    width: px(15.55);
  }
}
Enter fullscreen mode Exit fullscreen mode

Now over many files I didn't want to manually replace all the values. What I found was this:
Image description

Top comments (0)