How to detect the last 2 words using Javascript?

Just try with:

var testing = sample.split(" ").splice(-2);

-2 takes two elements from the end of the given array.


Note that splice again give an array and to access the strings again the you need to use the index which is same as accessing directly from splitted array. Which is simply

var words =sample.split(" ");
var lastStr = words[words.length -1];
var lastButStr = words[words.length -2];

If you prefer the way you are doing. you are almost there. Pop() it again.

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

var sample = "Hello World my first website";
var words= sample.split(" ");
var lastStr = words.pop(); // removed the last.
var lastButStr= words.pop();
console.log(lastStr,lastButStr);

Note , pop() removes the element. And make sure you have enough words.

Tags:

Javascript