3

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.

Mohit Yadav
  • 145
  • 1
  • 12
  • Maybe this: `[\\\\]/\\//g` in the end. It seems that you do not need the parentheses. – Nikolay Handzhiyski Oct 17 '21 at 08:55
  • It also seems that you do not need and the brackets: `\\\\/\\//g` – Nikolay Handzhiyski Oct 17 '21 at 09:08
  • On testing, you do need the brackets `[\\\\]/\\//g`. In theory, you should be able to find a way to not use the brackets but I think there may be a bug in the snippet resolution with the escapes within the transform. You can see this because something like `\\\\t/\\//g` works - without brackets, if you know a `t` follows the \. But otherwise the escapes are screwing up the second `/` in the transofrm. – Mark Oct 17 '21 at 14:49
  • I guess the brackets help to isolate the \\\\'s from the next / but should not strictly be necessary. – Mark Oct 17 '21 at 15:11
  • Thank you @NikolayHandzhiyski, it worked for me. Sorry for late reply. – Mohit Yadav Oct 23 '21 at 16:17

1 Answers1

0

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

Nikolay Handzhiyski
  • 1,360
  • 1
  • 6
  • 20