Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the last 2 words using Javascript?

Tags:

javascript

Hi sorry for the simple question but how can I detect the last two words in the String?

Let say I have this var:

var sample = "Hello World my first website";

How can I get the last two words dynamical. I tried the split().pop but only the last word is getting

var testing = sample.split(" ").pop();
console.log(testing)
like image 949
VLR Avatar asked Jul 20 '17 07:07

VLR


People also ask

How do you select the last word in JavaScript?

To get the last word of a string:Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.

How do I find the last second index?

length - 1 . By subtracting 1 from the last index, we get the index of the second to last array element.

How do I get the last character in a JavaScript string?

Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.

How do you search for a word in JavaScript?

The search() method returns the index (position) of the first match. The search() method returns -1 if no match is found. The search() method is case sensitive.


4 Answers

Just try with:

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

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

like image 128
hsz Avatar answered Oct 21 '22 13:10

hsz


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.

like image 23
Suresh Atta Avatar answered Oct 21 '22 12:10

Suresh Atta


Or do it with a regex if you want it as a single string

var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/[^ ]* [^ ]*$/g);
console.log(res);
like image 3
Herr Derb Avatar answered Oct 21 '22 13:10

Herr Derb


var splitted = "Hello World my first website".split(" ");
var testing = splitted.splice(splitted.length - 2);
console.log(testing[0] + " " + testing[1]);
like image 1
old_account Avatar answered Oct 21 '22 12:10

old_account