regexvisual-studio-codevscode-snippets

Replace backslash '\' with forward '/' slash in VS Code snippets with Regex


Background:

I am adding a custom JavaScript snippet in VS Code to insert the file path of the current file. VS Code provides variables to get the file path but the file path contains backslashes in the path. And I want to get the path with '/' instead of '\'

eg. 'hello\world.js' -> 'hello/world.js'

VS Code also provides variable transformations using regex. I tried to replace backslashes with forward slashes but I could not make it work. I also checked similar questions but I could not any result for this specific to variable transformations in VS Code snippets. And I could not figure it out with other similar solutions as I'm new to regex.

What I tried:

This works fine and replaces backslashes '\' with '_'

"filepath": {
  "prefix": "filepath",
  "body": ["/${RELATIVE_FILEPATH/([\\\\])/_/g}"],
  "description": "Path of current file"
}

But if I change '_' with '/' it does not work.

"filepath": {
  "prefix": "filepath",
  "body": ["/${RELATIVE_FILEPATH/([\\\\])///g}"],
  "description": "Path of current file"
}

I tried some variations by escaping slash and using regex groups but I could not make it work.


Solution

  • \\\\/\\//g is your expression. That one should mean the same, because it is a choice of only one character: [\\\\]/\\//g.