【问题标题】:Spliting the URL path and getting only 2 parts of it拆分 URL 路径并仅获取其中的 2 个部分
【发布时间】:2017-04-24 20:38:58
【问题描述】:

我需要拆分用户输入的路径并只抓取其中的一部分。例如如果用户输入路径为:

/content/mypath/myfolder/about/images/April/abc.jpg

我应该这样理解:

四月/abc.jpg

$(document).ready(function(){
  $('#getData').click(function(){
    imgPath = $('#imgPath').val();

    console.log($(imgPath).split('/'));

    //console.log(slicedPath);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Image path: <input type="text" id="imgPath">
<button id="getData">Click</button>

【问题讨论】:

  • 所以基本上你只想要文件名和父文件夹?
  • 很难给出明确的答案。通过示例,您可以提供更多问题。你的意思是只有图像之后的路径吗?你是说只有最后两个孩子吗?
  • 直到我回答你已经问过这个完全相同的问题后才意识到。为什么?
  • 哦!..对不起,我想我错过了,不知何故!

标签: jquery html arrays split


【解决方案1】:

split() 返回一个数组。拆分后,您可以像这样获得其中的任何部分:

$(document).ready(function(){
  $('#getData').click(function(){
    var imgPath = $('#imgPath').val();

    var split = imgPath.split('/');
    
    var desiredPath = split[split.length-2] + "/" + split[split.length-1];
    
    console.log(desiredPath);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Image path: <input type="text" id="imgPath">
<button id="getData">Click</button>

【讨论】:

    【解决方案2】:

    当您使用split 时,它会将数据拆分为array。然后您可以使用array[number] 来获取特定值。

    $(document).ready(function(){
      $('#getData').click(function(){
        imgPath = $('#imgPath').val();
        var s = imgPath.split('/');
        var l = s.length - 1;
        console.log(s[(l - 1)] + "/" + s[l]);
    
        //console.log(slicedPath);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    Image path: <input type="text" id="imgPath">
    <button id="getData">Click</button>

    【讨论】:

      【解决方案3】:

      你可以使用pop在拆分后从最后一个获取值,

      str = '/content/mypath/myfolder/about/images/April/abc.jpg';
      var a = str.split('/');
      second = a.pop();
      first = a.pop();
      url = first+"/"+second;
      console.log(url);
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

      编辑:

      你可以有更优化的方式,

      str = '/content/mypath/myfolder/about/images/April/abc.jpg';
          var a = str.split('/');
          arr = [];
          arr.push(a.pop(),a.pop());
          str = arr.reverse().join("/");
          console.log(str);
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

      优势:

      通过这种方式,您可以从 url 的最后一侧拥有两个以上(如果需要),因此它可以灵活地实现两个以上的部分。

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-15
        • 2019-06-15
        • 2014-10-27
        • 2011-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多