【问题标题】:File Directory - Replace Backward Slash "\" with Forward Slash "/"文件目录 - 将反斜杠“\”替换为正斜杠“/”
【发布时间】:2018-08-30 22:36:11
【问题描述】:

我每天都会将网页文件保存在公共驱动器上。然后我必须将 html 文件的直接链接发送给客户端。

为此,我倾向于手动将文件夹目录中的所有反斜杠“\”转换为正斜杠“/”,并在开头添加“http://”。

例子:

\\Public\Drive\PageLocation\
http://Public/Drive/PageLocation/index.html

我已经开始使用查找和替换选项,但我觉得如果有某种代码可以在输入字段中转换这些路径会更好。

以下是我的想法的简要介绍:

*{font-family:sans-serif;}

p{
  font-weight:bold;
 }
<p>Folder Directory to URL </p>
<input type="text" placeholder="\\Public\Drive\PageLocation\">
<input type="submit" value="Convert">
<br>

<span>Result: http://Public/Drive/PageLocation/index.html</span>
<br/><br/>

<p>URL to Folder Directory </p>
<input type="text" placeholder="http://Public/Drive/PageLocation/index.html">
<input type="submit" value="Convert">
<br>

<span>Result: \\Public\Drive\PageLocation\</span>

我已经尝试弄清楚 JavaScript RegExp,但我没有找到太多的运气使它能够正常工作。似乎它只能读取双反斜杠并忽略单打:

var FolderDirectory = "\\Public\Drive\PageLocation";
var URLConvert = FolderDirectory.replace(/\\/g, "/");
alert(URLConvert);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;

是否有转换斜线的热键之类的东西?
你们都用什么?
有没有其他方法可以在本地转换斜杠?
你会推荐什么?

谢谢。

【问题讨论】:

    标签: javascript html directory directory-structure


    【解决方案1】:

    问题已经是你的起始字符串了。反斜杠被解释为转义字符。所以它们不存在于字符串中。但是,如果您想在 HTML 表单中输入路径,则字符串确实已经以正确的方式包含反斜杠。请参阅此处的简短示例。

        function convert(){
            var src_url = document.getElementById("path").value;
            var converted_url = src_url.replace("\\\\", "http://").replace(/\\/g, "/");
            alert(converted_url);
        }
    <input type="text" id="path" value="\\Public\Drive\PageLocation\">
    <input type="button" value="convert" onclick="convert()">

    【讨论】:

    • 非常好!感谢分享:)
    【解决方案2】:

    您的正则表达式是完美的,问题是您正在更改的字符串。在 javascript 中,反斜杠 (\) 用于转义字符。

    反斜杠 (\) 转义字符将特殊字符转换为字符串字符...
    Javascript Strings

    这是您想要做的工作示例:

    document.getElementById('input').onkeyup = function() {
      //when someone types in the input
      var v = this.value; //input's value
      if (v[0] === '\\') {
        //text entered is a url
        //                                add 'http:'        replace \ with /
        document.getElementById('result').textContent = 'http:' + v.replace(/\\/g, '/');
      } else {
        //text entered is a path
        //                                            remove http or https     replace / with \
        document.getElementById('result').textContent = v.replace(/https?:/g, '').replace(/\//g, '\\');
      }
    }
    <input type=text placeholder="enter file path or url" id=input>
    <p id='result'></p>

    【讨论】:

    • 哇,非常感谢!完美运行 :) 令我惊讶的是,您可以根据 url 和路径的输入值进行转换以适应自身。
    • 是的,没问题!
    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多