2017-04-21 94 views
1

我需要拆分用户输入的路径,并只抓取它的某个部分。 例如如果使用的路径为:在jQuery中拆分URL路径并获取其中的一部分

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

然后我只想显示images/abc.jpg

我越来越

Uncaught Error: Syntax error, unrecognized expression

错误的时刻。

这里是我的代码。

$(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>

+0

'.val()'返回一个字符串,而不是DOM元素。要求jQuery包装它不会起作用。只需使用'imgPath.split('/')' – Tibrogargan

+0

获取最后一部分的标准是什么?你正在寻找某个单词(即“图像”)还是你在一个文件和直接父母之后? – Tibrogargan

+0

最后一部分应该只是一个图像名称,后跟图像扩展名。 – Sunny

回答

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>

-1

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

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

+0

这是我希望的正确解释! –

1

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

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


     }); 
}); 
+0

或更简洁:'theArray.split(-2).join('/')' – Tibrogargan

+0

这是supa .... – Vbudo