javascript
Get first 10 words from string javascript
September 18, 2022
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
- Split the string using split(/\s+/) function. It will split the string using space and return the array.
- On the above array, apply the slice(0, 10) function to get the array of 10 words from the String.
- 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);
Was this helpful?
Similar Posts
- Replace multiple spaces between words with single space using javascript
- Array.find() - get the very first element satisfy a condition Javascript
- Lodash - get the first element from an array
- Lodash - Get index of first occurence of an array value
- Add new item at first position of array using unshift() method Javascript
- Remove first n elements from an array using Lodash
- Create random string in Javascript