Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Returning lengthy words from a string using JavaScript
We are required to write a JavaScript function that takes in a sentence of words and a number. The function should return an array of all words greater than the length specified by the number.
Problem Statement
Input:
const str = 'this is an example of a basic sentence'; const num = 4;
Expected Output:
const output = [ 'example', 'basic', 'sentence' ];
Because these are the only three words with length greater than 4.
Using for Loop
The most straightforward approach is to split the string into words and iterate through them:
const str = 'this is an example of a basic sentence';
const num = 4;
const findLengthy = (str = '', num = 1) => {
const strArr = str.split(' ');
const res = [];
for(let i = 0; i < strArr.length; i++){
const el = strArr[i];
if(el.length > num){
res.push(el);
}
}
return res;
};
console.log(findLengthy(str, num));
[ 'example', 'basic', 'sentence' ]
Using Array.filter() Method
A more concise solution using the filter() method:
const str = 'this is an example of a basic sentence';
const num = 4;
const findLengthyWords = (str, num) => {
return str.split(' ').filter(word => word.length > num);
};
console.log(findLengthyWords(str, num));
[ 'example', 'basic', 'sentence' ]
Using Regular Expressions
For more complex word extraction, you can use regular expressions to handle punctuation:
const str = 'Hello, this is an example! Basic sentence.';
const num = 4;
const findLengthyWordsRegex = (str, num) => {
const words = str.match(/\b\w+\b/g) || [];
return words.filter(word => word.length > num);
};
console.log(findLengthyWordsRegex(str, num));
[ 'Hello', 'example', 'Basic', 'sentence' ]
Comparison
| Method | Code Length | Handles Punctuation | Performance |
|---|---|---|---|
| for Loop | Longer | No | Good |
| Array.filter() | Shorter | No | Good |
| Regular Expression | Medium | Yes | Slower |
Conclusion
Use Array.filter() for clean, readable code when working with simple spaces. For text with punctuation, consider the regex approach to properly extract words.
Advertisements
