Get the first N words from a String using JavaScript

Javascript get first n words of string example; In this tutorial you will learn how to get first N words from a string using JavaScript;

Example 1:

In Javascript to get the first N words from a string we can use split method on the string, with an empty space and use the slice method to slice N words then Join the results on an empty space.

const str = 'This is a test string';

// First 3 words
const first3 = str.split(' ').slice(0, 3).join(' ');
console.log(first3); // This is a 

// First 2 words
const first2 = str.split(' ').slice(0, 2).join(' ');
console.log(first2); // This is

Example 2:

The Array.slice method returns a new array, containing the words we wanted to keep.

const str = 'This is a test string';

const sliced = str.split(' ').slice(0, 2); // ['This', 'is']
console.log(sliced);

Example 3:

We pass a whitespace character to the join method to join the array elements into a string, where the words are separated by spaces.

const str = 'This is a test string';

const split = str.split(' ') 
console.log(split) // ['This', 'is', 'a', 'test', 'string']