JavaScript Program to Find Words which are Greater than given Length k
Last Updated :
23 Feb, 2024
In JavaScript, to find words that are greater than the given length k, we need to split an array into words and then filter out words based on their lengths.
Using split and filter methods
In this approach, we split the input string into an array of words using the split() method and then filter the array to retrieve the words whose length is greater than the given value ‘k’ using the filter() method.
Syntax:
let res = str.split(" ").filter(word => word.length > k).join(" ");
Example: The below example uses split and filter methods to find words that are greater than the given length k in JavaScript.
Javascript
let str = "hello geeks for geeks is computer science portal" ;
let k = 4;
let res = str.split( " " )
.filter(word => word.length > k);
console.log(res.join( " " ));
|
Output
hello geeks geeks computer science portal
Using forEach and an empty array
In this approach, we initialize an empty array and iterate over each word in the input string using forEach. For each of the words that is greater than the k value is pushed into the result array and printed as the output.
Syntax:
let res = [];
str.split(" ").forEach(word => word.length > k && result2.push(word));
result2.join(" ");
Example: The below example uses forEach and empty array to find words that are greater than the given length k in JavaScript.
Javascript
let str = "hello geeks for geeks is computer science portal" ;
let k = 4;
let res = [];
str.split( " " ).forEach(word => {
if (word.length > k) {
res.push(word);
}
});
console.log(res.join( " " ));
|
Output
hello geeks geeks computer science portal
Using RegEx
In this approach, we use a regular expression (‘/\s+/’) to split the input string into an array of words. Using the filter() method we get the words that are greater in length than the k value.
Syntax:
let res = str.split(/\s+/).filter(word => word.length > k).join(" ");
Example: The below example uses RegEx to find words that are greater than the given length k in JavaScript.
Javascript
let str = "hello geeks for geeks is computer science portal" ;
let k = 4;
let res = str.split(/\s+/)
.filter(word => word.length > k);
console.log(res.join( " " ));
|
Output
hello geeks geeks computer science portal
Share your thoughts in the comments
Please Login to comment...