javascript

Get first 10 words from string javascript

There are multiple ways to get the first N words from a String using Javascript. You can use regex in order to do that or you can also use split() function of Javascript. We will explain them one by one in this post.

function getWordStr(str) {
    return str.split(/\s+/).slice(0, 10).join(" ");
}

//TO CALL THIS FUNCTION
var fullStr = "We can get first 10 words form this string using the above function";
var finalStr = getWordStr(fullStr);

console.log(finalStr);

Output

We can get first 10 words form this string using

The code snippet can be used to get the first 10 words from a string. You can set start and end points in the 'getWordStr' function. We have applied a start point from 0 and an endpoint to 10.

We are using regex here to get the first 10 words from the String. We can write it in one line as below.

const result = "Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor".split(/\s+/).slice(0, 10).join(" ");

console.log(result);

// -> Lorem ipsum dolor sit amet consectetur adipiscing elit sed do

Steps to get the first N words from String using Regex

  1. Split the string using split(/\s+/) function. It will split the string using space and return the array.
  2. On the above array, apply the slice(0, 10) function to get the array of 10 words from the String.
  3. Join the above array using the join('  ') function.

Get first N words from String without using regex

const mystr = "Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor"

const result = mystr.split(' ').slice(0, 10).join(" ");

console.log(result);

Live Demo

Was this helpful?