【问题标题】:Splitting a URL path in jQuery and getting a part of it在 jQuery 中拆分 URL 路径并获取其中的一部分
【发布时间】:2017-04-21 04:25:10
【问题描述】:

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

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

那我只想显示images/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>

【问题讨论】:

  • .val() 返回一个字符串,而不是一个 DOM 元素。要求 jQuery 包装它是行不通的。只需使用imgPath.split('/')
  • 获取最后一部分的标准是什么?您是在寻找某个词(即“图像”)还是在寻找文件和直接父级?
  • 最后一部分应该只是一个图像名称,后跟图像扩展名。

标签: javascript jquery arrays url split


【解决方案1】:

$(imgPath) 将尝试定位imgPath 是选择器的元素。由于用户输入的路径不是正确的选择器,它会抛出错误。 例如,如果用户输入/content/mypath/myfolder/about/images/abc.jpg,则选择器将是$('/content/mypath/myfolder/about/images/abc.jpg'),这不是有效的表达,因此会出现错误。

您可以使用正则表达式来获取图像路径

imgPath.match(/images\/.*$/i)[0]

正则表达式将匹配images/ 后跟任意数量的字符。 match返回一个数组,所以使用[0]会得到图片路径。

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

    console.log(imgPath.match(/images\/.*$/i)[0]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
Image path: <input type="text" id="imgPath" value="/content/mypath/myfolder/about/images/abc.jpg">
<button id="getData">Click</button>

【讨论】:

    【解决方案2】:

    我假设想要最后两个路径值。

    $(document).ready(function(){
         $('#getData').click(function(){
         imgPath = $('#imgPath').val();
    
     var theArray = imgPath.split('/');  // split path into parts
    
     // take the last two indexes to form short path
     var shortPath = theArray[theArray.length - 2] + '/' + 
                     theArray[theArray.length - 1];
    
    
          });
    });
    

    【讨论】:

    • 或更简洁:theArray.split(-2).join('/')
    【解决方案3】:

    您应该使用console.log(imgPath.split("/")) 而不是console.log($(imgPath).split("/"))

    这里imgPath只是一个存储输入值的变量,而不是用作$(imgPath)的dom元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 2011-10-20
      • 1970-01-01
      • 2014-10-27
      • 2011-12-15
      • 2017-03-03
      • 2021-10-09
      相关资源
      最近更新 更多