0

I want to read directory path to convert Windows directory to Linux directory.

I tried this:

"C:\Users\503176332\dashboard\Dashboard-sans-swirl\pcm-dashboard\src\app\components\admin"
  .replace(new RegExp(/\\/g), "/")

Output: "C:Users(3176332dashboardDashboard-sans-swirlpcm-dashboardsrcappcomponentsadmin".

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • But in the string literal itself backslashes should be _escaped_. Your current string literal contains no backslashes: `"\50"` is `"("`, but `"\\50"` is a backslash followed by `"50"`, and so on. If you get the path from somewhere else (where backslashes are already part of the string), the method call would indeed work, although the `RegExp` constructor is unnecessary here. Just do `path.replace(/\\/g, "/")` or [`path.replaceAll("\\", "/")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll#Browser_compatibility). – Sebastian Simon Jul 20 '20 at 18:53
  • Does this answer your question? [Javascript and backslashes replace](https://stackoverflow.com/questions/2479309/javascript-and-backslashes-replace) (Ignore the answer by thegajman). – Sebastian Simon Jul 20 '20 at 19:05
  • 1
    There are no backslashes in the string to start with. If you have this somewhere as string literal use `"\\"` for a single backslash. A backslash is a special character inside string context and should be escaped (with another backslash). This is so you can type `"\n"` which becomes a newline character instead of the literal ``\`` followed by the literal `n`. So the string should be: `"C:\\Users\\503..."` – 3limin4t0r Jul 20 '20 at 19:18
  • 1
    ^ See: [MDN Grammar and types - Using special characters in strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings) – 3limin4t0r Jul 20 '20 at 19:24

1 Answers1

0

If you literally try the string "C:\Users\503176332\dashboard\Dashboard-sans-swirl\pcm-dashboard\src\app\components\admin", then JavaScript interprets each \ as an escape character, and also the regex is not correct: instead of new Regexp(/\/g) you can just put /\\/g, as backslash is an escape character we need to put it twice. The same applies to you path constant.

If you try this:

"C:\\Users\\503176332\\dashboard\\Dashboard-sans-swirl\\pcm-dashboard\\src\\app\\components\\admin".replace(/\\/g,"/")

it will give you this:

"C:/Users/503176332/dashboard/Dashboard-sans-swirl/pcm-dashboard/src/app/components/admin"
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
slkorolev
  • 5,883
  • 1
  • 29
  • 32
  • Backslash is also used as an escape character in the Markdown editor here. You need to format your code as code, especially if it contains backslashes. The question source never contained `new Regexp(/\/g)`. It contained `new RegExp(/\\/g)` all along, which _is_ correct, but overkill. – Sebastian Simon Jul 20 '20 at 19:07