拆分URL路径并获取其中的2个部分
问题描述:
我需要拆分用户输入的路径,并只抓取其中的一部分。对于例如如果用户输入路径为:拆分URL路径并获取其中的2个部分
/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>
答
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>
答
当您使用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>
答
您可以使用流行到拆分后从去年中取值,
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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
编辑:
你可以有更优化的方式,
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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
优势:
通过这种方式,您可以有两个以上(如果你想)从最后一面因此它的url灵活性可以达到两个以上的部分。
我希望这会有所帮助。
所以基本上你只想要文件名和父文件夹? –
很难给出明确的答案。通过这个例子,你提供了更多的问题。你的意思只是图像之后的路径吗?你只是指最后两个孩子吗? – manuzi1
[在jQuery中拆分URL路径并获取其中的一部分]的可能副本(http://*.com/questions/43533945/splitting-a-url-path-in-jquery-and-getting-a-part它的) –