0

I want all single backslashes to be converted into double backslash

"C:\Users\MyName\ringtone.mp3" --> "C:\\Users\\MyName\\ringtone.mp3"

But for some reason it returns "C:UsersMyNameingtone.mp3"

So far I have tried the escape() function and the encodeURI() function but they don't work either. Partial of the string comes from nodejs OS Module which only returns with a single backslash on windows (homedir() function). Here is what I have so far in the function

function normalize(path: string): string {
   return path.normalize().replace(/\\/g, '\\');
}

Thanks in Advance

sam patel
  • 145
  • 1
  • 8
  • replace by "\\\\" instead of "\\", Reason:- because "\" is a escape character so "\\" is interpreted as `\" so you need "\\\\" to have "\\" – Code Maniac Oct 03 '19 at 02:06
  • 1
    I just tested `os.homedir()` and it correctly has slashes. can you post a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve) of your nodejs script so we can see how you are using the value? – jtate Oct 03 '19 at 02:22

1 Answers1

1

This should work:

var original = 'C:\\Users\\MyName\\ringtone.mp3';
var replaced = original.normalize().replace(/\\/g, '\\\\');

console.log('Original: ' + original);
console.log('Replaced: ' + replaced);

From what I see you had 2 problems:

First, it seems you were initializing your string like this:

var original = 'C:\Users\MyName\ringtone.mp3'

This would make your actual string value C:UsersMyNameingtone.mp3 because a \ character in javascript symbolizes an escape character.

Second, is because the \ character is an escape character, so the '\\' in your replace function is only looking to replace the matching pattern with a single backslash.

jtate
  • 2,612
  • 7
  • 25
  • 35
  • 2
    An explanation about _why_ this works would be nice. – Tim Biegeleisen Oct 03 '19 at 02:06
  • Thats the problem, the input string comes from the machine(nodejs OS module) itself not the user which is creating the problem. – sam patel Oct 03 '19 at 02:07
  • if your input string is garbage (aka doesn't have actual slash characters) then there is nothing you can do. you can't replace a slash that isn't there. – jtate Oct 03 '19 at 02:12