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
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);
0 Comments