-1

How can I get the first 3 words from a string and add them to the last 3 words of the same string and skip the text in the middle.

For ex.,

The string "I have something important to tell you guys"

The result should be the string "I have something tell you guys" (first 3 words and last 3 words)

My code:


let myString = "I have something important to tell you guys";
let myArray = "I have something important to tell you guys";

myArray = myArray.split(' ')
let firstThreeWords = myArray[0] + " " + myArray[1] + " " + myArray[2];
let lastThreeWords = ... //not sure what to put here

console.log(firstThreeWords + lastThreeWords)

I got the first 3 words but how can I get the last 3 words if we don't know the exact number of words in a string?

Iryshka Ka
  • 11
  • 4
  • and [Get first word of string](https://stackoverflow.com/questions/18558417/get-first-word-of-string), [Javascript: Returning the last word in a string](https://stackoverflow.com/questions/20883404/javascript-returning-the-last-word-in-a-string) – pilchard Dec 21 '22 at 11:37

2 Answers2

0

You can try something like that

let myString = "I have something important to tell you guys";
let myArray = myString.split(' ');

const firstThree = myArray.slice(0, 3).join(' ');
const lastThree = myArray.slice(-3).join(' ');

const result = firstThree + " " + lastThree;
console.log(result);
Ben
  • 598
  • 3
  • 12
0
    let myString = 'I have something important to tell you guys';
let myArray = 'I have something important to tell you guys';

myArray = myArray.split(' ');
let firstThreeWords = myArray[0] + ' ' + myArray[1] + ' ' + myArray[2] + ' ';
let lastThreeWords =
  myArray[myArray.length - 3] +
  ' ' +
  myArray[myArray.length - 2] +
  ' ' +
  myArray[myArray.length - 1];
console.log(firstThreeWords + lastThreeWords);

get you're last three words from the string by decreasing the length of the array.