admin管理员组文章数量:1415095
Is it possible to use string split in javascript to get the last element in the array that is produced.
For example, im sure in php you can do the same and use a negative limit value to get the last item i.e. -1 or the last two items -2 etc.
Is it possible to use string split in javascript to get the last element in the array that is produced.
For example, im sure in php you can do the same and use a negative limit value to get the last item i.e. -1 or the last two items -2 etc.
Share Improve this question edited Aug 6, 2010 at 17:58 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Aug 6, 2010 at 15:57 daviddavid 111 silver badge2 bronze badges3 Answers
Reset to default 6You can use slice
on the result array you get from split
:
"Lorem ipsum dolor sit amet consectetur".split(/ /).slice(-2) // returns ["amet", "consectetur"]
There's a pop() method that removes and returns the last element of an array:
"/path/to/somefile.jpg".split("/").pop();
// -> "somefile.jpg"
As Gumbo mentioned, slice() will allow you to select a range of array elements.
pop and splice are what you are after
var a = "1,2,3,4,5";
var b = a.split(/,/g).pop();
var a1 = a.split(/,/g);
var c = a1.splice(a1.length-2,a1.length);
var d = a.split(/,/g).splice(-2);
本文标签: arraysjavascript string split negativeStack Overflow
版权声明:本文标题:arrays - javascript string split negative - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745183231a2646562.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论