function longestWord(string) {
var str = string.split(\" \");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
for (var i = 0; i < str.length - 1; i++)
to
for (var i = 0; i <= str.length - 1; i++)
OR
for (var i = 0; i < str.length; i++)
I think this is more easy
function findLongestWord(str) {
var longestStr = 0;
for (var x=0;x<str.split(' ').length;x++){
if (longestStr < str.split(' ')[x].length){
longestStr = str.split(' ')[x].length;
}
}
return longestStr;
}
Thanks everyone, this is the fixed code:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[i].length; j++) {
if (/[a-zA-Z]/.test(str[i][j])) {
checkedLetters += str[i][j];
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
}
return word;
}
That's because you're not comparing all the items in the array, you leave out the last one.
for (var i = 0; i < str.length - 1; i++)
should be
for (var i = 0; i < str.length; i++)
or
for (var i = 0; i <= str.length - 1; i++)
I would say using the forEach loop is the most understandable version
function longestWord(sen) {
big_word = ""
words = sen.split(" ")
words.forEach(function(word){
if (word.length > big_word.length){
big_word = word
};
});
return big_word
};
Code below will find the largest word and its length from a string. Code is in plain JavaScript and html.
function findLongestWord() {
var str = document.getElementById('inputText').value;
calculateLength(str);
}
function calculateLength(str) {
var substring = str.split(" ");
var minChar = '';
for (var i = 0; i <= substring.length - 1; i++) {
if (substring[i].length >= minChar.length) {
minChar = substring[i];
}
}
document.getElementById('longChar').innerHTML = 'Longest Word: ' + minChar;
document.getElementById('longCharLength').innerHTML = 'Longest Word length: ' + minChar.length;
}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<input type="text" id="inputText"> <br/>
<button onclick=findLongestWord()>Click to find longest word</button> <br/>
<div id="longChar"></div> <br/>
<div id="longCharLength"></div>
</body>
<script src="longestWord.js"></script>
</html>