拆分在jQuery的一个URL路径,并获得它的一部分(Splitting a URL path in

2019-09-27 23:57发布

我需要拆分用户输入的路径,并抓住它只是某一部分。 对于例如,如果使用的进入路径:

/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> 

Answer 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> 



Answer 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];


      });
});


Answer 3:

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

这里imgPath仅仅是存储输入值,而不是一个DOM元素被用作可变$(imgPath)



文章来源: Splitting a URL path in jQuery and getting a part of it