LongestWord javascript
LongestWord javascript
Have you ever faced a situation where you need to find the longest word in a string? Well, JavaScript has got you covered. Here are a few ways you can achieve this:
Method 1:
You can use the split()
method to split the string into an array of words and then use a loop to iterate through the array and find the longest word. Here's the code:
function longestWord(str) {
var words = str.split(' ');
var maxLength = 0;
var longestWord = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
longestWord = words[i];
}
}
return longestWord;
}
console.log(longestWord('The quick brown fox jumped over the lazy dog')); // Output: 'jumped'
Method 2:
You can also achieve this using the reduce()
method. Here's the code:
function longestWord(str) {
var words = str.split(' ');
var longestWord = words.reduce(function(longest, currentWord) {
return currentWord.length > longest.length ? currentWord : longest;
}, '');
return longestWord;
}
console.log(longestWord('The quick brown fox jumped over the lazy dog')); // Output: 'jumped'
Method 3:
If you want to be fancy, you can use map()
, sort()
, and pop()
to achieve the same result. Here's the code:
function longestWord(str) {
var words = str.split(' ');
var sortedWords = words.map(function(word) {
return word.replace(/[^\w]/g, '');
}).sort(function(a, b) {
return b.length - a.length;
});
return sortedWords[0];
}
console.log(longestWord('The quick brown fox jumped over the lazy dog')); // Output: 'jumped'
These are just a few ways you can find the longest word in a string using JavaScript. Choose the one that works best for your use case.