How to usesplit() and for…loop in Javascript
Here, we will split the string and before that, we will declare an empty string in order to store the resulted from the longest string in it. Also, we will be using an arrow function and this whole task will be performed under it only.
Example: This example uses the above-explained approach.
// JavaScript code to for the above approach..
let longestWord = (string) => {
let stringg = string.split(" ");
let longest = 0;
let longest_word = null;
for (let i = 0; i < stringg.length; i++) {
if (longest < stringg[i].length) {
longest = stringg[i].length;
longest_word = stringg[i];
}
}
return longest_word;
};
console.log(
longestWord(
"Hello guys this is w3wiki where students learn programming"
)
);
Output
w3wiki
How to find the longest word within the string in JavaScript ?
To find the longest word within the string in JavaScript we will compare the counts to determine which word has the most characters and return the length of the longest word.
Example:
Input: "This is a demo String find the largest word from it"
Output: "largest"
Input: "Hello guys this is w3wiki where students learn programming"
Output: "w3wiki"
We can use the following approaches to find the longest word within the string in JavaScript:
Table of Content
- Using regex and for…loop
- By using the split() and sort() method
- Using split() and reduce() methods
- Using split() and for…loop
- Using sort() method