代码之家  ›  专栏  ›  技术社区  ›  oshirowanen

转换字符串

  •  0
  • oshirowanen  · 技术社区  · 16 年前

    如何转换字符串

    This:
    file:///C://Program%20Files//Microsoft%20Office//OFFICE11//EXCEL.EXE 
    
    To this:
    C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE 
    
    4 回复  |  直到 16 年前
        1
  •  3
  •   Nick Craver    16 年前

    这样做的诀窍是:

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

    You can try it out here .

        2
  •  2
  •   BrunoLM    16 年前

    无景观,更换 file:/// 替代 // .

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

    退换商品

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

    对于单个反斜杠使用

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

    结果是

    "C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE"
    
        3
  •  0
  •   ocodo    16 年前

    使用 decodeURIComponent 修复 %20 和类似的URL转义字符。然后简单地将路径名(在字符串位置8之后)替换为 // 具有 \\ 使用拆分/联接。

    或者…

    var original = "file:///C://Program%20Files//Microsoft%20Office//OFFICE11//EXCEL.EXE ";
    
    var fixed = decodeURIComponent(original.substr(8)).split('//').join('\\');
    

    您可以使用replace代替split/join。

        4
  •  0
  •   Karel Petranek    16 年前

    此解决方案可避免不必要的替换:

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