Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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.
You can use slice on the result array you get from split:
slice
split
"Lorem ipsum dolor sit amet consectetur".split(/ /).slice(-2) // returns ["amet", "consectetur"]
Add a comment
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);
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.