1

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.

12
  • 1
    You first expression is OK, your string is not. It must be "\\\\pest-TS01\\Users\\pest\\Music\\musi\\New folder" May 10, 2016 at 9:34
  • Your pattern .replace(/\\/g, "/") works as expected.
    – Shafizadeh
    May 10, 2016 at 9:36
  • 1
    @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
    May 10, 2016 at 9:40
  • 3
    I don't understand downvotes. It is a valid question.
    – webduvet
    May 10, 2016 at 9:46
  • 1
    PS: I did not vote down - it is however a duplicate - for example stackoverflow.com/questions/2479309/…
    – mplungjan
    May 10, 2016 at 9:53

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.