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)
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.
length - 1 . By subtracting 1 from the last index, we get the index of the second to last array element.
Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.
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.
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.
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);
var splitted = "Hello World my first website".split(" ");
var testing = splitted.splice(splitted.length - 2);
console.log(testing[0] + " " + testing[1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With