在jQuery中拆分URL路径并获取其中的一部分

我需要拆分用户输入的路径并仅抓取其中的某些部分。 例如,如果使用输入路径为:

/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); }); }); 
  Image path:   

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

您可以使用RegEx来获取图像路径

 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]); }); }); 
  Image path:   

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

 $(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]; }); }); 

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

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