0

How do I convert a string

This:
file:///C://Program%20Files//Microsoft%20Office//OFFICE11//EXCEL.EXE 

To this:
C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE 
oshirowanen
  • 15,297
  • 82
  • 198
  • 350

4 Answers4

3

Something like this would do the trick:

function getPath(url) {
  return  decodeURIComponent(url).replace("file:///","").replace(/\//g,"\\");
}

You can try it out here.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
2

Unescape, replace file:/// and replace //.

// if you face problems with IE use `unescape` instead.
var d = decodeURIComponent("file:///C://Program%20Files//Microsoft%20Office//OFFICE11//EXCEL.EXE")
d = d.replace(/file:\/\/\//i, "").replace(/\/\//g, "\\\\");

Returns

"C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE"

For a single backslash use

d = d.replace(/file:\/\/\//i, "").replace(/\/\//g, "\\");

Which results in

"C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE"
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • You'd want to use `decodeURIComponent()` here instead of `unescape()`. They're not the same: http://stackoverflow.com/questions/619323/decodeuricomponent-vs-unescape-what-is-wrong-with-unescape – Nick Craver Oct 06 '10 at 13:11
0

This solution avoids unnecessary replaces:

var input = "file:///C://Program%20Files//Microsoft%20Office//OFFICE11//EXCEL.EXE";

// Remove file:///
if (input.length > 8 && input.substr(0, 8) == "file:///")
  input = input.substr(8);

input = decodeURIComponent(input).replace(/\/\//g, "\\\\"));
Karel Petranek
  • 15,005
  • 4
  • 44
  • 68
  • This would only replace the *first* `//` occurrence, JavaScript's a bit wacky like that, you need the global option to make it replace *all* occurrences. – Nick Craver Oct 06 '10 at 13:12
0

Use decodeURIComponent to fix the %20 and similar url escaped chars. Then simply substring out the pathname (after string position 8) and replace the // with \\ using split / join.

or...

var original = "file:///C://Program%20Files//Microsoft%20Office//OFFICE11//EXCEL.EXE ";

var fixed = decodeURIComponent(original.substr(8)).split('//').join('\\');

You could use replace instead of the split / join.

ocodo
  • 29,401
  • 18
  • 105
  • 117
  • See this question for reasons not to use `unescape()`: http://stackoverflow.com/questions/619323/decodeuricomponent-vs-unescape-what-is-wrong-with-unescape – Nick Craver Oct 06 '10 at 13:12