Get the first N words from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20211 min read

Get the first N words from a String in JavaScript #

To get the first N words from a string in JavaScript:

  1. Call the split method on the string, with an empty space
  2. Use the slice method to slice N words
  3. Join the results on an empty space
index.js
const str = 'A very long string'; // ๐Ÿ‘‡๏ธ First 2 words const first2 = str.split(' ').slice(0, 2).join(' '); console.log(first2); // ๐Ÿ‘‰๏ธ A very // ๐Ÿ‘‡๏ธ First 3 words const first3 = str.split(' ').slice(0, 3).join(' '); console.log(first3); // ๐Ÿ‘‰๏ธ A very long

In the code snippet, we first use the String.split method to split the string on a space.

This returns an array containing all of the words from the string as separate elements:

index.js
const str = 'A very long string'; const split = str.split(' ') // ๐Ÿ‘‰๏ธ ['A', 'very', 'long', 'string'] console.log(split)

We then call the Array.slice method, passing it a start index of 0 and an end index of however many words we want to get.

The end index argument of the Array.slice method means get the elements up to this index, but not including.

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

index.js
const str = 'A very long string'; const sliced = str.split(' ').slice(0, 2); // ๐Ÿ‘‰๏ธ ['A', 'very'] console.log(sliced);

The last step is to join the array elements into a string, by using the Array.join method.

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

index.js
const str = 'A very long string'; const first2 = str.split(' ').slice(0, 2).join(' '); console.log(first2); // ๐Ÿ‘‰๏ธ A very

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee