Get the first N words from a String in JavaScript

JavaScript provides versatile methods for manipulating strings, and extracting the first N words from a given string is a common requirement in many programming scenarios. In this article, we will explore various approaches and techniques to achieve this task effectively.

 

Method 1: Using the Split Method One straightforward method involves using the split method, which allows us to split a string into an array of substrings based on a specified delimiter. In this case, we can split the string using a space (' ') as the delimiter and then extract the first N elements from the resulting array.

 

const str = 'Mathira is love';

const first = str.slice(0, 1);
console.log(first);

const first3 = str.slice(0, 3);
console.log(first3);

const first5 = str.slice(0, 5);
console.log(first5 ); 


another example of getting first 5 word from a string



function getFirstNWords(inputString, n) {
 const wordsArray = inputString.split(' ');
 const firstNWords = wordsArray.slice(0, n).join(' ');
 return firstNWords;
}
// Example usage:
const originalString = "JavaScript provides versatile methods for manipulating strings.";
const result = getFirstNWords(originalString, 5);
console.log(result);

 

 

Method 2: Regular Expressions for Precision For a more precise solution, we can utilize regular expressions to account for various whitespace characters. This approach ensures better flexibility in handling different spacing scenarios between words.
 

 


function getFirstNWordsRegex(inputString, n) {
 	const wordsArray = inputString.match(/\S+/g) || [];
 	const firstNWords = wordsArray.slice(0, n).join(' ');
 	return firstNWords;
}
// Example usage:
const originalString = "JavaScript     regex  offers precise string manipulation methods.";
const result = getFirstNWordsRegex(originalString, 6);
console.log(result);

 

 

Conclusion: By exploring these methods, developers can choose the approach that best fits their specific requirements. Whether opting for the simplicity of the split method or the precision of regular expressions, JavaScript offers versatile tools for efficiently extracting the initial N words from a string.

Thank You


Tags:

Share:

Related posts