Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode deletes `\` on save from my regex pattern [duplicate]

I am trying to write the line:

const reg = new RegExp('\.js$');

but my VSCode deletes the \ from my regex on save. Is this a setting, or some issue with a plugin? Searched online, but wasn't finding any relevant answers.

For reference, plugins installed are: - Angular v5 Snippets - Beautify - CodeMetrics - Debugger for Chrome - EditorConfig for VSCode - npm - npm Intellisense - Prettier - TSLint - vscode-icons

like image 225
nyc_arts Avatar asked Mar 15 '18 00:03

nyc_arts


2 Answers

The offender is Prettier. If formatOnSave is activated in the editor/user settings

// Set the default
"editor.formatOnSave": true,
// Enable per-language
"[javascript]": {
    "editor.formatOnSave": true
}

it will remove \ in strings if it is not part of a valid escape sequence.
A valid escape sequence like \\ or \n is not affected. So, this is actually in your best interest.

like image 97
wp78de Avatar answered Sep 22 '22 01:09

wp78de


Whether this will fix your problem or not, I'm not sure, but that regex should be:

const reg = new RegExp('\\.js$');

Since you're doing the regex as a string, you need to double your backslashes to represent a single backslash.

Or you could do:

const reg = /\.js$/;

It could be that VSCode is deleting the backslash the way you originally wrote this because it's an invalid escape.

like image 26
kshetline Avatar answered Sep 21 '22 01:09

kshetline