views:

45

answers:

4

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 
+3  A: 

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
+2  A: 

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
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
A: 

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, "\\\\"));
dark_charlie
you missed the %20's
slomojo
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
Thanks, fixed that
dark_charlie
A: 

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.

slomojo
See this question for reasons not to use `unescape()`: http://stackoverflow.com/questions/619323/decodeuricomponent-vs-unescape-what-is-wrong-with-unescape
Nick Craver
updated. thanks.
slomojo