How to detect the last 2 words using Javascript?

Viewed 5347

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)
10 Answers

The problem can be solved in several ways. the one I prefer is the following that splits the problem in sub problem:

  1. transoform a sentence in an array
  2. get last 2 items of an array

Transform a sentence in an array

let sentence = "Server Total Memory Capacity is: 16502288 MB";
let sentenceAsArray = sentence.split(' ');

Get last items of an array

let numberOfItems = 2;
let lastTwo = sentenceAsArray.splice(-numberOfItems)

Join array items

At the beginning we transformed a sentence into an array. Now we have to do the complementary operation: transform an array into a sentece.

let merged = lastTwo.join(' ')

Print into console

Now that we have new variable with desired content, can show it printing variable into the console with the following command.

console.log(merged)

You can use substr function

var sample = "Hello World my first website";
var testing = sample.substr(sample.length -2);

Related