1
votes

In a case, I just wanted to replace all the back slashes with forward slash, but while trying to do that I am receiving some weird results.

Attempt 1:

"\\pest-TS01\Users\pest\Music\musi\New folder".replace(/\\/g, "/")

The above line yields the below result

"/pest-TS01UserspestMusicmusiNew folder"

Attempt 2:

var x = new RegExp("\\", "g");
"\\pest-TS01\Users\pest\Music\musi\New folder".replace(x, "/");

And the above code throws the following error,

Uncaught SyntaxError: Invalid regular expression: //: \ at end of pattern(…)


Expected result:

"//pest-TS01/Users/pest/Music/musi/New folder"

Can anyone give me a regex that matches the backslashes accurately? Also advise me on How to replace the matched back slashes with forward slashes. And I still believe that the regex that I have framed is correct, But why is it behaving weirdly?


Special note:

Please do not suggest any solutions using string manipulations like split() and something similar to that. I am looking for regex answers and need to find a reason why my regex is not working.

1
You first expression is OK, your string is not. It must be "\\\\pest-TS01\\Users\\pest\\Music\\musi\\New folder" - Wiktor Stribiżew
Your pattern .replace(/\\/g, "/") works as expected. - Shafizadeh
@WiktorStribiżew Why would you say that? A correct pattern should work for every kind of string... So your string isn't OK makes no sense. - Shafizadeh
I don't understand downvotes. It is a valid question. - webduvet
PS: I did not vote down - it is however a duplicate - for example stackoverflow.com/questions/2479309/… - mplungjan

1 Answers

2
votes

Use String.raw(), convert single \ to \\ and finally \\ to /

string = String.raw`\\pest-TS01\Users\pest\Music\musi\New folder`;
result = string.replace(/\b[\\]{1}\b/g, "/").replace(/\\+/, "/");
document.write(result);

I honestly don't know what's happening behind the scenes with the singles back-slashes, but I guess they're being escaped.