Mediocre
Mediocre

Reputation: 301

Replacing all back slashes with forward slash

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.

Upvotes: 1

Views: 367

Answers (1)

Pedro Lobito
Pedro Lobito

Reputation: 98921

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.

Upvotes: 2

Related Questions