arrays - javascript string split negative - Stack Overflow

Is it possible to use string split in javascript to get the last element in the array that is produced.

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 badges
Add a ment  | 

3 Answers 3

Reset to default 6

You 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745183231a4615515.html

相关推荐

  • arrays - javascript string split negative - Stack Overflow

    Is it possible to use string split in javascript to get the last element in the array that is produced.

    12小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信