开发者

Converting a string

开发者 https://www.devze.com 2023-01-19 02:45 出处:网络
How do I convert a string This: file:///C://Program%20Files//Microsoft%20Office//OFFICE11//EXCEL.EXE To this开发者_如何学运维:

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 


Something like this would do the trick:

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

You can try it out here.


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"


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.


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, "\\\\"));
0

精彩评论

暂无评论...
验证码 换一张
取 消